1

我有个问题。我想知道IN当双方都有多个值时如何使用语句(在查询中) - 我正在编写一个查询:

SELECT name FROM math_Details WHERE cric_ids in (1,2,3,4,8);

在此查询问题中,cric_ids列中还有多个值通过 (,comma) 分隔;喜欢(5,9,1,10,2)

请帮我?

4

2 回答 2

1

可以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.

于 2012-06-07T13:25:42.740 回答
0

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,

  1. make a full query and with PHP functions get the values (you can convert it to into an array and get the values), it will be SO SLOW!.....
  2. Redesign your database (recommended) to fix that and futures conflicts.

Please take a look to database entity relationship model and normalization.

于 2012-06-07T13:18:12.693 回答