簡體   English   中英

從同一表中選擇與一串用逗號分隔的值匹配的所有行

[英]Select all rows matching a string of comma separated values from same table

我的表結構是這樣的:

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

存儲這樣的數據不好(意味着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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM