表格1

+----+--------+
| id | name   |
+----+--------+
|  2 | robin  |
|  3 | jyothi |
|  1 | angel  |
+----+--------+

表2
+----+---------+--------+
| id | hobbies | ref_id |
+----+---------+--------+
|  1 | walking |      1 |
|  2 | chating |      1 |
|  3 | reading |      2 |
|  4 | walking |      2 |
+----+---------+--------+

我想要名字和他们的爱好,他们的爱好是“散步”或名字是“知更鸟”
+----+-----------------+
| name | hobbies       |
+----+-----------------+
|  1 | walking,chating |
|  3 | reading,surfing |
+----+-----------------+

使用过的查询:
select name, group_concat(hobbies) as all_hobbies
from test1,test2
where test1.id = test2.ref_id
and test1.id in (select ref_id
              from test2
              where hobbies = 'walking')
group by name

我不想使用子查询或将整个结果保存为虚拟表,并通过where子句在all_hobbies上进行搜索。我想通过where子句或以某种方式完成group_concat列,因为它增加了我的SQL_JOIN_SZIE

我不能在这里使用它,因为它必须充当或条件,例如:

爱好是“散步”还是名字是“知更鸟”

最佳答案

我没有在这台机器上安装mysql,但是尝试执行此查询,我认为它应该可以工作。您可以将HAVING子句视为WHEREGROUP BY子句。

select name, group_concat(hobbies) as all_hobbies
from test1,test2
where test1.id = test2.ref_id and test1.name = 'robin'
group by name
having all_hobbies like '%walking%'

关于mysql - 如何将过滤条件放在group_concat列上?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7204625/

10-11 07:36