简体   繁体   中英

MySQL Grouping SubQuery Optimization

I have a table of Categories, and a table of Products. Products have a category_id, and also a maker_id.

I am attempting to return a table of Category Names, along with a Binary of whether or not the category contains any products that belong to a given $maker_id (as defined in PHP code).

My current method counts how many matching products are in each category, but I'm assuming there is a faster way since I only need a Yes/No. Current code:

SELECT 
    c.name,
    SUM(CASE WHEN p.maker_id = '{$maker_id}' THEN 1 ELSE 0 END) AS already_used
FROM categories c
LEFT JOIN products p ON p.category_id = c.id
GROUP BY c.id

I'm reading up on using EXISTS, but all the examples I've found are using it in the WHERE clause. Thanks!

You can try this:

SELECT c.name,COUNT(1) AS already_used, SUM(IF(p.status = 'ready', 1, 0)) AS ready_count 
FROM categories c 
LEFT JOIN products p 
ON  (p.category_id = c.id)
WHERE  p.maker_id = '{$maker_id}'
GROUP BY c.id;

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