我有很多疑问,可以将它合并为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
答案 0 :(得分:2)
我认为这对你有用。它将在单个SQL语句中返回3个计数:
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
这是SQL Fiddle。
祝你好运。答案 1 :(得分:1)
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
您将从一个很长的列表中的所有查询中获取多行。
答案 2 :(得分:0)
您可以使用:
select sum( x ) from query 1 union query 2 etc
答案 3 :(得分:0)
试试这个
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