我有个问题。我想知道IN
当双方都有多个值时如何使用语句(在查询中) - 我正在编写一个查询:
SELECT name FROM math_Details WHERE cric_ids in (1,2,3,4,8);
在此查询问题中,cric_ids
列中还有多个值通过 (,comma) 分隔;喜欢(5,9,1,10,2)
请帮我?
你可以FIND_IN_SET()
重复使用 MySQL 的函数:
SELECT name
FROM math_Details
WHERE FIND_IN_SET(1, cric_ids) OR FIND_IN_SET(2, cric_ids)
OR FIND_IN_SET(3, cric_ids) OR FIND_IN_SET(4, cric_ids)
OR FIND_IN_SET(8, cric_ids)
这样的语句可以在 PHP 中动态构建。例如,在PDO中使用准备好的语句:
$set = [1,2,3,4,8];
$sql = 'SELECT name FROM math_Details WHERE FALSE'
. str_repeat(' OR FIND_IN_SET(?, cric_ids)', count($set));
$qry = $dbh->prepare($sql);
$qry->execute($set)
但是,正如其他人所说,这表明数据库设计不佳。您应该考虑规范化您的数据结构,以便cric_ids
您拥有一个math_Details
与每个cric
.
oh man, your design is so mess up that what you are asking is almost impossible, what I understand is that you have:
Select name from math_Details where cric_ids in (1,2,3,4,8);
and the column looks like this:
| cric_ids |
-------------
|1,2,3,5,4 |
|5,8,6,12,3|
|78,6,2,4,6|
|5,7,8,9,1 |
and you want to be able to make search by digits....
the like wont help you because the result is a string or varchar, so your possible options could be (beside that you need to use a 'like' for each option)
critics like '1' //wont work at least you only have 1 in your cric_ids
critics like '%1' // will work only if 1 is the last value
critics like '1%' //will work only if 1 is the first vaue
critics like '%1%' // will give you all values with 1, like 1, 10, 11, 111, 19, etc...
I think you have 2 options,
Please take a look to database entity relationship model and normalization.