thevoipman
thevoipman

Reputation: 1833

Combining 2 Mysql queries into one

I currently running two queries to find one result, I have a good feeling I can combine these two queries into one. I've tried the method below but it's still showing me results that already appear from access_number table.

$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;
   }
}

I tried combining it like this and it's not showing me unique values

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

Bottom line is, I'm trying to find a value in table access_number that does not exist in customer_dd

Any kind of help I can get on this is greatly appreciated!

Upvotes: 1

Views: 52

Answers (2)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

You may use left join and not null for this

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

Upvotes: 1

Leo Silence
Leo Silence

Reputation: 1192

your code:

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

base on you code, i found your table access_number.did = customer_dd.did.

so you can try:

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

Upvotes: 0

Related Questions