当使用像'%%'这样的HAVING x时,group_concat返回空,但是不像WHERE x那样'%%'

时间:2012-07-13 20:50:08

标签: mysql

在下面的示例查询中,我将提取与关键字匹配的所有文本,并按年份分割结果。我更喜欢搜索'text' - 所有字符串的连接版本,而不是仅使用WHERE子句对每个字段进行搜索,但是HAVING不返回任何数据:

SELECT 
date_format(created_date, '%Y-%m') as yr_mo,
count(id),
group_concat(coalesce(title,''),coalesce(story,'') SEPARATOR ' ') as text
from input_form
where dupe = 0 /*and story like '%flood%'*/
group by yr_mo
having text like '%flood%'
order by yr_mo

下面是当我取消注释/ **和故事'%flood%'** /并删除HAVING子句时返回的内容:

yr_mo   count(id)   text
2011-04 2   Floods Roads in my  community one time proved to b...
2011-05 21  THE TRUSTED LADY.   It was during my usual visits ...
2011-06 22  HEAVY RAINFALL On our village we were affected wit...
2011-07 52  FEED THE CHILDREN PROGRAMME(1) The world food prog...
2011-08 29  I was saved and helped to prosperI am one of the v...
2011-09 15  FLOODS In the past three months the country have f...
2011-10 19  FLOODFlood is a very bad disaster at the same time...
2011-11 9   RESPONDING TO DISASASTERUNICEF landed over relief ...
2011-12 3   EARLY PREVENTION OF FLOODShaving sensed the likeli...
2012-01 44  HUNGER STRIKE             In Wataalamu village the...
2012-04 8   THE FALLEN BRIDGEThe Kambu bridge along the Mombas...
2012-05 7   Increasing earth's natural environment awarenessAf...
2012-06 4   A misery solvedRecently 10 people died in my commu...
2012-07 21  Lsot HopesWhen the Agricultural Farmers Society ca...

我尝试过使用coalesce避免空值(故事,''),但结果是一样的。

编辑#1:我找到了一个更长,更乱的查询工作,并提供了我想要的东西:

SELECT 
date_format(created_date, '%Y-%m') as yr_mo,
count(if( ( story like '%hunger%' OR title like '%hunger%' ) and (story_location_city like '%nairobi%' OR story_location_neighborhood like '%nairobi%'),id,null)) as 'hunger',
count(if( ( story like '%poverty%' OR title like '%poverty%' ) and (story_location_city like '%nairobi%' OR story_location_neighborhood like '%nairobi%'),id,null)) as 'poverty',
count(if( ( story like '%school%' OR title like '%school%' ) and (story_location_city like '%nairobi%' OR story_location_neighborhood like '%nairobi%'),id,null)) as 'school',
count(id) as total
from input_form
where dupe = 0
group by yr_mo
order by yr_mo

如果必须,我可以在if()语句中搜索每个字段,它将提供特定的结果。有没有更有效的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

GROUP_CONCAT truncates its output to (by default) 1024 characters,因此HAVING子句要求字符串flood出现在连接文本的前1024个字符中,而WHERE子句仅要求它出现 {/ 1>}中的某处

即使不是截断,我认为input_form.story + GROUP_CONCAT也不是你想要的,因为那将包括所有记录任何任何匹配记录的月份。例如,如果2012年4月有20条记录,但只有10条记录包含HAVING,则flood + GROUP_CONCAT方法(如果不是截断的话)表示有20条匹配记录2012年4月,将包括所有这些文本。