2011-09-19 28 views
1

我有返回类似于行这样的产品搜索查询:MySQL的逻辑结果跨越多个行

| id | name | search tag | 
| 1 | cat | furry  | 
| 1 | cat | ginger | 
| 2 | dog | furry  | 

我需要做的是能够得到符合多个搜索标签单列 - 对于这个例子,搜索毛茸茸的AND姜没有返回行,因为每行只有一个搜索标签(这是因为要得到这些结果,我使用的是INNER JOIN)。

我的问题是,我需要做什么才能够在查询中测试furry AND ginger并返回该猫而不是狗?

我在做这个。


UPDATE

为了应对用户重复标记放,一个简单的修复到HAVING条件将返回有重复的标签,而不是忽视他们行:

mysql> select id, name, group_concat(tag) as tags, 
count(tag) as cnt from animals where tag in ('furry', 'ginger') 
group by id HAVING cnt>=2; 

回答

4

你可以首先选择具有所需标签的行,然后通过动物ID将它们分组。计算每只动物获得的结果数量,以及与希望得到匹配的标签数量相同。

mysql> select id, name, group_concat(tag) as tags, 
count(tag) as cnt from animals where tag in ('furry', 'ginger') 
group by id HAVING cnt=2;  
+----+------+--------------+-----+ 
| id | name | tags   | cnt | 
+----+------+--------------+-----+ 
| 1 | cat | furry,ginger | 2 | 
+----+------+--------------+-----+ 
+0

这工作完美,谢谢。一些* *的concat出现在我身上,但我从来没有使用过group_concat(),所以也谢谢你:) – jammypeach