MySQL COUNT(子查询)

时间:2011-05-06 08:01:13

标签: mysql count subquery

我的MySQL查询:

 SELECT id, name, depth, restricted, order, parent_id,
    (SELECT COUNT(t2.id) AS count FROM #__webshop_product_color_dbar AS t2
        WHERE t2.product_id =
            (SELECT product_id FROM #__webshop_category_product AS t3
            WHERE t3.category_id = "0")
        AND available < 0 OR stock = "Y" OR infinite_amount = "Y"
    ) AS productcount
    FROM #__webshop_category AS t1
    WHERE parent_id = "'.$parent_id.'" AND depth = "'.$depth.'" AND restricted="N"
    ORDER BY id ASC

我的问题是:所有产品数量= 2; 如果我使用“WHERE t2.product_id IN”,它就不起作用。

有什么问题?

(抱歉我的英语不好)

1 个答案:

答案 0 :(得分:0)

子选择未链接到t1.id,以下连接将恢复该链接 如果没有关于表之间关系的更多信息,我不是100%确定它是你想要的,但它应该是接近的。

SELECT t1.id, t1.name, t1,depth, t1.restricted, t1.order, t1.parent_id
  , COUNT(t2.id) as productcount
FROM #__webshop_category AS t1
LEFT JOIN #__webshop_product_color_dbar AS t3 on (t3.category_id = t1.id)
LEFT JOIN #__webshop_product_color_dbar AS t2 ON 
  (
  t2.product_id = t3.product_id AND t2.available < 0 
    OR stock = 'Y' OR infinite_amount = 'Y'
  )
WHERE t1.parent_id = "'.$parent_id.'" 
  AND t1.depth = "'.$depth.'" 
  AND t1.restricted = 'N'
GROUP BY t1.id

请注意,GROUP BY已经对项目ASC进行了排序,因此不需要额外的ORDER BY