开发者

MySQL COUNT(subquery)

开发者 https://www.devze.com 2023-03-03 01:44 出处:网络
My MySQL query: SELECT id, name, depth, restricted, order, parent_id, (SELECT COUNT(t2.id) AS count FROM #__webshop_p开发者_运维知识库roduct_color_dbar AS t2

My MySQL query:

 SELECT id, name, depth, restricted, order, parent_id,
    (SELECT COUNT(t2.id) AS count FROM #__webshop_p开发者_运维知识库roduct_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

My problem is: all product count = 2; if i use "WHERE t2.product_id IN", it does not work.

What is the problem?

(Sorry for my bad english)


The subselects are not linked to t1.id, The following joins restores that link.
I'm not 100% sure it's what you want without more info on the relationships between the tables, but it should be close.

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

Note that the GROUP BY already orders the items ASC, so no extra ORDER BY is needed.

0

精彩评论

暂无评论...
验证码 换一张
取 消