[英]How to write this mysql query
id | term | result
==================
1 | t1 | 0
2 | t2 | 0
3 | t1 | 34
4 | t1 | 23
5 | t2 | 10
6 | t2 | 10
7 | t3 | 20
该表用于搜索表,其中term是某人正在搜索的关键字,而result是当时返回的结果数。 现在,从此表中,我需要检索1)搜索术语的次数,以及2)上次搜索时返回的结果数。
对于第一个,我可以count(term) group by term
进行count(term) group by term
,对于2个,我可以ORDER by id DESC
,但是我不知道如何在单个查询中同时进行这两个操作。 有什么帮助吗?
您可以使用GROUP_CONCAT()函数汇总结果字段,然后使用SUBSTRING_INDEX取回您想要的那个。
SELECT COUNT(term), SUBSTRING_INDEX(GROUP_CONCAT(result ORDER BY id DESC), ',', 1) FROM table GROUP BY term
select term, count(*), (select result from my_table where id = max(t.id))
from my_table t
group by term
请参见SQL Fiddle
使用以下查询
select id,term,count(*) as 'count',result from (select * from table33
order by id desc) as abc group by term
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.