我有一个sql查询,由于链接产品的产品id重复,它返回了一些不正确的结果,所以我在查询的末尾添加了以下内容,希望它只接受任何产品id的第一个实例:
AND pc.products_id
IN
(SELECT
pc.products_id, MIN(categories_id)
FROM
zen_products_to_categories pc
GROUP BY
pc.products_id)
但是当我运行进程时,我得到的操作数应该包含1列错误。我自己运行了这个查询,它只给我每个产品id一次,所以不确定为什么会出现错误。
我现在的完整查询是:
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
有人能告诉我为什么当我添加额外的查询时它不起作用吗,因为它让我感到困惑
您可以尝试使用:
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)
编辑:
在MySQL中,像这样的子查询通常很慢。你应该有更好的运气加入:
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
....
当您与单列匹配时,子查询应该返回一列。从子查询中删除MIN(categories_id)
AND pc.products_id
IN
(SELECT
pc.products_id
FROM
zen_products_to_categories pc
GROUP BY
pc.products_id)