MySQL查询与数组值

时间:2017-06-25 11:43:12

标签: mysql

我现在正在使用这个简单的查询:

SELECT * FROM ships ORDER BY shipid ASC

现在我有一系列应该搜索的船只......

$shipid = array("1","9","19","73");

有没有办法在没有循环的情况下轻松执行 ONE 查询,也无法构建查询字符串?

我正在寻找类似的东西:

SELECT * FROM ships WHERE shipid=(IS IN ARRAY shipids) ORDER BY shipid ASC

谢谢!

2 个答案:

答案 0 :(得分:2)

您必须使用IN子句

SELECT * FROM ships WHERE shipid IN (1,9,19,73) ORDER BY shipid ASC

您可以创建如下所示的查询字符串

<?php
$ships = array("1","9","19","73");
$query = "SELECT * FROM ships WHERE shipid IN (".implode(',',$ships).") ORDER BY shipid ASC";
?>

以下是它如何生成查询字符串

<强>脚本

akshay@db-3325:/tmp$ cat test.php 
<?php
$ships = array("1","9","19","73");
$query = "SELECT * FROM ships WHERE shipid IN (".implode(',',$ships).") ORDER BY shipid ASC";
print $query.PHP_EOL;
?>

<强>输出

akshay@db-3325:/tmp$ php test.php 
SELECT * FROM ships WHERE shipid IN (1,9,19,73) ORDER BY shipid ASC

答案 1 :(得分:2)

尝试使用php implode()函数将数组转换为字符串,如:

$ships = implode(",", ships);

并使用它:

"SELECT * FROM ships WHERE shipid IN (".$ships.") ORDER BY shipid ASC"