操作数应包含1列错误

时间:2013-11-28 07:40:08

标签: mysql sql operand mysql-error-1241

我有一个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 

任何人都可以告诉我为什么当我添加额外的查询时它不起作用因为它让我感到困惑

2 个答案:

答案 0 :(得分:1)

您可以尝试:

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中,像这样的子查询通常很慢。你应该好好加入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
  ....

答案 1 :(得分:0)

当您与子列中的单个列删除MIN(categories_id)匹配时,子查询应返回一列

AND pc.products_id 
IN
(SELECT
pc.products_id
FROM
zen_products_to_categories pc
GROUP BY
pc.products_id)