选择与同一个表中的逗号分隔值字符串匹配的所有行

时间:2015-07-15 14:43:23

标签: mysql sql

我的表结构是这样的:

row_id    col_1     col_2
------    ------    ------
1         title1     2,4,5
2         title2     1,2
3         title3     4
4         title4     2,5
5         title5     3,4

我想从col_1中选择col_2中存在row_id的所有标题。

因此,例如,如果我只查询第一行,我希望查询返回:

1 | title1 | title2, title4, title5

1 个答案:

答案 0 :(得分:0)

这样存储数据并不好(意味着col2字段,更具体地说,存储以逗号分隔的值)。您应该查看规范化并将col_2数据存储在另一个表中,每个值都有一个单独的行。

例如:

create table tbl1 (
  row_id int primary key,
  col_1 varchar(20)
);

create table tbl2 (
  parent_id int,
  child_id  int, /* col_2 in your example */
  foreign key (parent_id) references tbl1(row_id),
  foreign key (child_id) references tbl1(row_id)
);

然后您可以轻松获得所需的结果:

select t2.parent_id
     , group_concat(t1.col_1)
from tbl2 t2
join tbl1 t1 on t1.row_id = t2.child_id
where t2.parent_id = 1
group by t2.parent_id

SQLFiddle