多个WHERE和查询 - Mysql / PHP

时间:2012-08-23 07:57:46

标签: php mysql

尝试将一个查询的结果放入另一个查询的WHERE语句中:

$query1 = "SELECT DISTINCT company_id FROM location WHERE state = 'XX'";
$result1 = mysql_query($query1) or die(mysql_error());
while($row1 = mysql_fetch_array($result1)) {
    //Collect WHERE STATEMENT HERE
}

我尝试了以下内容:

$q1 = "SELECT company FROM company WHERE id = '16', id = '7' ORDER BY company";
$q1 = "SELECT company FROM company WHERE id = '16' AND id = '7' ORDER BY company";
$q1 = "SELECT company FROM company WHERE id = '16' && id = '7' ORDER BY company";

与其他变体一起

如果使用不同的表名,谷歌搜索只提供了多个WHERE AND,但不一样。任何人有任何指针?

3 个答案:

答案 0 :(得分:1)

您也可以使用IN

$x = array('16', '7');

$q1 = "SELECT company FROM company WHERE id IN(". implode(',', $x) .") ORDER BY company";

答案 1 :(得分:1)

用于通用代码:

$ids = array (
[0] => 2
[1] => 4
[2] => 19
[3] => 16
);  

$ids = join(',',$ids);  
$sql = "SELECT * FROM company WHERE id IN ($ids)";

reffer:same example

答案 2 :(得分:0)

使用OR

$q1 = "SELECT company FROM company WHERE (id = '16' OR id = '7') ORDER BY company";