简体   繁体   中英

MySQL COUNT(subquery)

My MySQL query:

 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM