Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a row from one table where the value row does not exist in another table?

Tags:

sql

Let's say I have two identical tables, A and B, with the row "x".

I want to select all elements in A, where the value of x in A is not in any value of x of B.

How do I do that?

like image 307
TravisG Avatar asked Dec 27 '22 00:12

TravisG


2 Answers

You could also do something like this:

SELECT * FROM TableA
LEFT JOIN TableB on TableA.X = TableB.X
WHERE TableB.X IS NULL

(For the very straightforward example in your question, a NOT EXISTS / NOT IN approach is probably preferable, but is your real query is more complex, this is an option you might want to consider; if, for instace, you want som information from TableB where there is a match, but also want to know where there isn't one)

like image 89
David Hedlund Avatar answered Jan 25 '23 22:01

David Hedlund


I'm having some trouble to understand what you need.
Anyway try this:

SELECT * FROM tableA 
WHERE x not IN (SELECT x FROM tableB)
like image 40
Marco Avatar answered Jan 25 '23 22:01

Marco