SQL从数组中选择IN子句?

时间:2011-08-18 07:49:47

标签: php sql arrays postgresql

我有一个清单

$list = array('a','b','c','d','e','f');
$filter_list = join(", " $list);
select * from test where id_col=12 and try_col in ($filter_list);

任何人都可以告诉我怎么能这样做。?

1 个答案:

答案 0 :(得分:3)

$list = array('a','b','c','d','e','f');
$filter_list = "'" . join("', '", $list) . "'";
$query = "select * from test where id=12 and try_col in ($filter_list)";
// select * from test where id=12 and try_col in ('a', 'b', 'c', 'd', 'e', 'f')

请注意,如果您的数组值包含',则会失败。这是一个解决方法:

$list = array("a'a",'a\a','b','c','d','e','f');
$temp = array_map("addslashes", $list);
$query = "SELECT * FROM test WHERE id=12 AND try_col in ('" . implode("','", $temp) . "')";
// SELECT * FROM test WHERE id=12 AND try_col in ('a\'a','a\\a','b','c','d','e','f')