Group concat的问题

一张表如下:
id | field
1 | 黄色
1 | 绿色
3 | 100g
3 | 60g
4 | 黄色

以id分组,把field字段的值打印在一行
select id,group_concat(field) from 表 group by id;
|1 | 黄色,绿色|
|3 | 60g,100g|
|4 | 黄色

问题是分组之后想把field字段为黄色的筛选出来,那么id是1和4的都应该被筛选出来,这个要怎么实现?如果用模糊查询感觉不准确,比如有条数据为'黄色12',那么这条也会被搜出来的,结果不准确

阅读 3.2k
4 个回答

这样子??
其实不是太明白你说的意思,最好你能在补充一点数据源数据。

select *from
(select id,group_concat(field) field from
(
select 1 id,'黄色' field from DUAL
union ALL
select 1 id,'绿色' field from DUAL
union ALL
select 4 id,'黄色' field from DUAL
union ALL
select 1 id,'12g' field from DUAL
) t group by id ) main
where main.field like '%黄色,%' or main.field like '黄色'

select field, group_concat(id) from 表 group by field

SELECT
    id,
    GROUP_CONCAT(field) fields
FROM
    test2
GROUP BY
    id
HAVING
    FIND_IN_SET('绿色', fields)

贴一下结果:
clipboard.png
另外贴一下黄色的结果:
clipboard.png

只需要跟原表再关联一次即可,效率可能差点:

select a.* from (select id,group_concat(field) from 表 group by id) a join 表 b on a.id=b.id where b.field='黄色';
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进