mysql - 选择 WHERE 子句,拆分列值并检查

标签 mysql sql

我有以下表架构

id   name     type
1    ABC      1,2,3,4
2    PQR      2,3,5 
3    XYZ      1,4
4    TCS      3,1
5    PPP      2,3

这里我想要如下显示结果,即类型为 1 和 4。
结果:-

id   name     type
1    ABC      1,2,3,4
3    XYZ      1,4
4    TCS      3,1

最佳答案

您可以使用FIND_IN_SET()功能:

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters.
Returns 0 if str is not in strlist or if strlist is the empty string.

SELECT * FROM Table1
WHERE
     FIND_IN_SET(1, type)
  OR FIND_IN_SET(4, type)

输出:

╔════╦══════╦═════════╗
║ ID ║ NAME ║  TYPE   ║
╠════╬══════╬═════════╣
║  1 ║ ABC  ║ 1,2,3,4 ║
║  3 ║ XYZ  ║ 1,4     ║
║  4 ║ TCS  ║ 3,1     ║
╚════╩══════╩═════════╝

See this SQLFiddle

SQLFiddle with more data

关于mysql - 选择 WHERE 子句,拆分列值并检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16535403/

相关文章:

mysql - 缺少数据库连接 cakephp

MySQL Union All - 值优先

sql - 有没有一种方法可以在Oracle 10g中的数据库之间复制BLOB记录?

mysql - 如何从表中选择不同的行并将所选行连接到 mysql 中的另一个表

java - 具有多个连接参数的 MySQL 连接字符串?

MYSQL 在时间戳上选择日期

sql - 如何使用 MySQL 索引列?

php - 更新sql查询不会通过php中的mysqli_query()更新记录

mysql - 选择 where image_url=0 但返回所有行?

sql - 如何从 select 语句添加插入到表中