user2014429
user2014429

Reputation: 2577

exclude duplicate results from second mysqli query

I have 2 mysqli query's and I want to exclude identical result values from the second query that have already been yielded by the first query. so if there are 2 tables like this:

table1:               table2:

       column                 column
       -------                -------
          1                      1
          2                      6
          3                      7
          4                      3                     
          5                      8

the results for the first query would be:

1,2,3,4,5

and the results for the second query would be:

6,7,8  

here is what I have tried:

$query1 = $db->query("SELECT column FROM table1");
$query2 = $db->query("SELECT column FROM table2");

while ($result1 = $query1 ->fetch_assoc()) {
  echo $result1['column']."<br>";
}
while ($result2 = $query2 ->fetch_assoc()) {
 if($result2['column'] !==  $result1['column']){ // this part is not working
    echo $result2['column']."<br>"; 
  }
 }

but the condition is not effective. Thanks.

Upvotes: 0

Views: 166

Answers (2)

BlargleMonster
BlargleMonster

Reputation: 1622

It will put a bit more of a load on the SQL server but you can do it easily in the SQL still as two seperate queries:

SELECT column FROM table1;
SELECT column FROM table2 WHERE column NOT IN (SELECT column FROM table1);

You could probably also get a little fancier and make it one query returning two columns if you would like that instead but I'd have to actually try it out against a database to make sure I had it right.

Upvotes: 0

juergen d
juergen d

Reputation: 204794

You can solve that in SQL directly. Use union to get only 1 result:

SELECT column_1 as result_column FROM table1
union
SELECT column_2 as result_column FROM table2

If the columns are named differently you can use an identical alias

Upvotes: 2

Related Questions