如何按id序列使用where子句

时间:2015-12-16 10:43:44

标签: mysql sql select in-operator

我有一个由逗号合并的ids序列:

$ids = '1,2,3,4,5,6,7,8,9,10' ;
select * from ads WHERE id = $ids ...

现在如何通过这些ads获取ids表的内容?

2 个答案:

答案 0 :(得分:3)

您正在使用PHP。您可以像这样构建SQL:

$ids = '1,2,3,4,5,6,7,8,9,10';
$sql = 'SELECT * FROM ads WHERE id IN ('.$ids.')';
//execute the query (don't use mysql_* function ;) )

自MySQL 5.6起,您也可以使用FIND_IN_SET()

$ids = '1,2,3,4,5,6,7,8,9,10';
$sql = "SELECT * FROM ads WHERE FIND_IN_SET(id, '".$ids."')";
//execute the query (don't use mysql_* function ;) )

答案 1 :(得分:2)

使用IN运算符

试试这个:

SELECT * 
FROM ads 
WHERE id IN ($ids);