0

在下面的示例查询中,我正在提取与关键字匹配的所有文本并按年月拆分结果。我更喜欢搜索“文本”——所有字符串的连接版本,而不是只针对每个带有 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(story,'') 避免空值,但结果是一样的。

编辑#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() 语句中的每个字段,它会提供特定的结果。没有更有效的方法来做到这一点吗?

4

1 回答 1

2

GROUP_CONCAT将其输出截断为(默认情况下) 1024 characters,因此该HAVING子句要求字符串flood出现在连接文本的前 1024 个字符内,而该WHERE子句仅要求它出现input_form.story.

即使不是为了截断,我认为GROUP_CONCAT+HAVING也不会是您真正想要的,因为这将包括具有任何匹配记录的任何月份的所有记录。例如,如果 2012 年 4 月有 20 条记录,但只有 10 条包含,那么+方法将(如果不用于截断)表示 2012 年 4 月有 20 条匹配记录,并将包含所有这些记录中的文本。floodGROUP_CONCATHAVING

于 2012-07-13T20:55:45.760 回答