【问题标题】:SQL: how to select rows where id is in comma separated string?SQL:如何选择 id 在逗号分隔的字符串中的行?
【发布时间】:2021-08-26 17:38:27
【问题描述】:

我认为我犯了一个大错误,我不知道该怎么做:

我有一个表格,其中包含房间列表和列成员 (varchar),其中包含以逗号分隔的接受成员 ID 列表 (Es. 1,2,15,1000)

我需要选择 id IN members 字符串的所有房间。任何想法???类似的东西

SELECT * FROM rooms WHERE id IN rooms.members

(我知道这行不通,但我希望我自己解释一下^^')

编辑 我需要在 PHP 中使用 PDO 进行 sql 查询,我使用的是 MySQL,目标是获取成员列表字符串中列出 id 的所有行的列表

【问题讨论】:

  • 请注明您的数据库管理系统的版本。
  • 我必须用 php 做一个 sql 查询,你为什么需要我的 dbms?反正是 MySQL
  • 是 MySQL 8 还是任何旧版本?
  • @Chris DBMS 很重要,因为 SQL 是特定于供应商的(有时也是特定于版本的)。任何答案都需要考虑您的数据库。客户端(此处为 php)通常与数据库引擎无关。

标签: mysql sql arrays string select


【解决方案1】:

在 MySQL 中,您可以使用 Find_in_set() 来完成您的工作:

DB-Fiddle:

 create table test (id int, studentIDs  varchar(50));
 insert into test values(1,'1,2,3');
 create table student (id int, name  varchar(50));
 insert into student values(1,'A');
 insert into student values(2,'B');

查询:

 select * from student where find_in_set(id,(select studentids from test))

输出:

id name
1 A
2 B

db小提琴here

如果您使用的是 sql server 2016 或更高版本,则可以使用 string_split()

DB-Fiddle:

 create table test (id int, studentIDs  varchar(50));
 insert into test values(1,'1,2,3');
 create table student (id int, name  varchar(50));
 insert into student values(1,'A');
 insert into student values(2,'B');

查询:

 select * from student where id in (select trim(value) from test cross apply string_split(studentids,','))

输出:

id name
1 A
2 B

db小提琴here

【讨论】:

  • 我正在使用 MySQL :/
  • @Chris 我已经为 MySQL 添加了答案。
  • 多亏了您的提示,我自己才找到了解决方案,而且是一样的!为你点赞!
  • 那太好了。为你的努力点赞。最良好的祝愿。
猜你喜欢
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多