我有很多疑问,可以将它组合成1来优化吗?
SELECT COUNT(prod_id) FROM products WHERE inventory <= 5 AND cat_id = 1
SELECT COUNT(prod_id) FROM products WHERE inventory BETWEEN 5 AND 10 AND cat_id = 1
SELECT COUNT(prod_id) FROM products WHERE inventory > 10
I think this should work for you. It will return the 3 counts in a single SQL statement:
SELECT SUM(CASE WHEN inventory <= 5 AND cat_id = 1 THEN 1 ELSE 0 END) Q1Result,
SUM(CASE WHEN inventory BETWEEN 5 AND 10 AND cat_id = 1 THEN 1 ELSE 0 END) Q2Result,
SUM(CASE WHEN inventory > 10 THEN 1 ELSE 0 END) Q3Result
FROM products
And here is the SQL Fiddle .
Good luck.
SELECT COUNT(prod_id) FROM products WHERE inventory <= 5 AND cat_id = 1
UNION ALL
SELECT COUNT(prod_id) FROM products WHERE inventory BETWEEN 5 AND 10 AND cat_id = 1
UNION ALL
SELECT COUNT(prod_id) FROM products WHERE inventory > 10
You'll get back multiple rows from the queries all in one big long list.
你可以使用:
select sum( x ) from query 1 union query 2 etc
Try this one
SELECT (
SELECT COUNT(prod_id) FROM products WHERE inventory <= 5 AND cat_id = 1
) AS count1,
(
SELECT COUNT(prod_id) FROM products WHERE inventory BETWEEN 5 AND 10 AND cat_id = 1
) AS count2,
(
SELECT COUNT(prod_id) FROM products WHERE inventory > 10
) AS count3
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.