我有很多查询,我可以将其合并为 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
我有很多查询,我可以将其合并为 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
我认为这应该对你有用。它将在单个 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。
祝你好运。
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
您将从查询中返回多行,全部放在一个大长列表中。
你可以使用:
select sum( x ) from query 1 union query 2 etc
试试这个
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