0

我的分类网站有九个类别。当用户搜索关键字时,我想显示搜索结果以及每个类别中的搜索结果数量。

如何优化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 查询更快吗?

4

3 回答 3

2

使用 GROUP BY 子句

SELECT
   COUNT(*)
   ,category_id 
FROM 
   ads 
WHERE 
   title like '%keyword%' 
GROUP BY category_id
于 2013-04-09T00:53:26.133 回答
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%' 
于 2013-04-09T02:16:33.477 回答
0

您可以通过 IF() (如果是 mysql)或 case/when 更通用的方式 sum() 计数

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%';
于 2013-04-09T03:54:07.110 回答