将2个Mysql查询合并为一个

时间:2015-05-13 04:23:55

标签: php mysql

我目前正在运行两个查询来查找一个结果,我很高兴我可以将这两个查询合并为一个。我已经尝试了下面的方法,但它仍然显示我已经从access_number表中显示的结果。

$query = "select * FROM `$table`.`access_number` WHERE `active`='1'"; 
$result = mysql_query($query,$db) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
  list($dd_inuse) = mysql_fetch_row(mysql_query("SELECT `did` FROM `$table`.`customer_dd` WHERE `did`='$row[did]' AND `callerid`='$callerid' LIMIT 1",$db));
  if(!$dd_inuse) {
     $goodone = $row['did'];
     break;
   }
}

我尝试将它组合起来,并没有向我展示独特的价值

select `access_number`.`did` from `access_number` 
INNER JOIN `customer_dd` 
WHERE `customer_dd`.`callerid`='$callerid' 
AND `customer_dd`.`did` !=`access_number`.`did` LIMIT 1

底线是,我正在尝试在access_number

中不存在的表customer_dd中找到一个值

非常感谢我能得到的任何帮助!

2 个答案:

答案 0 :(得分:1)

您可以将left joinnot null用于此

select 
a.access_number from access_number a
left join customer_dd c on c.did = a.did and c.callerid = '$callerid'
where c.did is null

答案 1 :(得分:0)

您的代码:

SELECT `did` FROM `$table`.`customer_dd` 
WHERE `did`='$row[did]' AND `callerid` = '$callerid' LIMIT 1

根据您的代码,我找到了您的表access_number.did = customer_dd.did

所以你可以尝试:

select `access_number`.`did` from `access_number` 
INNER JOIN `customer_dd` ON `customer_dd`.`did` = `access_number`.`did`
WHERE `customer_dd`.`callerid` = '$callerid' AND `access_number`.`active`='1' LIMIT 1