I have an sql query that was returning some incorrect results due to product id's being duplicated for linked products, so i added the following to the end of my query expecting it to only take the first instance of any product id:
AND pc.products_id
IN
(SELECT
pc.products_id, MIN(categories_id)
FROM
zen_products_to_categories pc
GROUP BY
pc.products_id)
But i get an Operand should contain 1 column(s) error when i run the process. I ran that query on it's own and it only gave me each product id once, so not sure why i get the error.
The full query i now have is:
SELECT p.products_quantity, p.abebooks_status,
p.products_id AS id,
p.products_status AS prodStatus,
FORMAT( IFNULL(s.specials_new_products_price, p.products_price),2) AS price,
pc.categories_id AS prodCatID,
c.parent_id AS catParentID,
cd.categories_name AS catName
FROM
zen_products p
JOIN zen_products_description pd ON p.products_id=pd.products_id
JOIN zen_products_to_categories pc ON p.products_id=pc.products_id
JOIN zen_categories c ON pc.categories_id=c.categories_id
JOIN zen_categories_description cd ON c.categories_id=cd.categories_id
left join zen_specials s on ( s.products_id = p.products_id AND ( (s.expires_date > CURRENT_DATE) OR (s.expires_date = 0) ) )
WHERE p.products_price > 0 and p.products_status = 1
AND pc.products_id
IN
(SELECT pc.products_id, MIN(categories_id)
FROM zen_products_to_categories pc GROUP BY pc.products_id)
ORDER BY catName ASC
Can anyone tell me why it doesn't work when i add the extra query because it's got me baffled
You could try with:
AND (pc.products_id, pc.categories_id)
IN
(SELECT
pc.products_id, MIN(categories_id)
FROM
zen_products_to_categories pc
GROUP BY
pc.products_id)
Edit:
In MySQL a subquery like this is usually slow. You should have better luck with a JOIN:
SELECT ....
FROM
....
INNER JOIN (SELECT
products_id, MIN(categories_id) min_categories_id
FROM
zen_products_to_categories
GROUP BY
products_id) min_ct
ON pc.products_id=min_ct.products_id
AND pc.categories_id=min_ct.min_categories_id
WHERE
....