我的classfieds网站有九个类别。当用户搜索关键字时,我想在每个类别中显示搜索结果和搜索结果的数量。
如何优化sql查询?
我尝试了什么?为每个类别运行一个循环:
select * from ads where title like '%keyword%';
select count(*) from ads where title like '%keyword%' and category_id = 1;
select count(*) from ads where title like '%keyword%' and category_id = 2;
select count(*) from ads where title like '%keyword%' and category_id = 3;
select count(*) from ads where title like '%keyword%' and category_id = 4;
.....
有什么更好的建议可以让sql查询更快?
答案 0 :(得分:2)
使用GROUP BY子句
SELECT
COUNT(*)
,category_id
FROM
ads
WHERE
title like '%keyword%'
GROUP BY category_id
答案 1 :(得分:0)
nickles80的查询将有效。但如果您想在一个查询中同时执行这两项操作,请尝试以下操作:
SELECT ads.*, cnt.CountResult
FROM ads
INNER JOIN (
SELECT category_id, COUNT(1) AS CountResult
FROM ads
where title like '%keyword%'
GROUP BY category_id
) cnt ON cnt.category_id = ads.category_id
where title like '%keyword%'
答案 2 :(得分:0)
你可以通过IF()(如果是mysql)来计算()计数,或者更多通用的情况/
select
count(*) as TotalAds,
sum( case when category_id = 1 then 1 else 0 end ) as TotalCategory1,
sum( case when category_id = 2 then 1 else 0 end ) as TotalCategory2,
sum( case when category_id = 3 then 1 else 0 end ) as TotalCategory3,
sum( case when category_id = 4 then 1 else 0 end ) as TotalCategory4,
sum( case when category_id = 5 then 1 else 0 end ) as TotalCategory5,
sum( case when category_id = 6 then 1 else 0 end ) as TotalCategory6,
sum( case when category_id = 7 then 1 else 0 end ) as TotalCategory7,
sum( case when category_id = 8 then 1 else 0 end ) as TotalCategory8,
sum( case when category_id = 9 then 1 else 0 end ) as TotalCategory9
from
ads
where
title like '%keyword%';