Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select data that exists in A but not in B

Imagine I have this tables: this tables.

What I need is to get the Data that exists in A but not in B, in this case my SELECT will have to return "2".

I've done it before, but right know I can't remember how. I suppose it was something like this:

SELECT a.*
FROM A as a
LEFT JOIN B AS b ON b.column = a.column

But it's not working. Can someone help me, please?

Thanks in advance.

like image 709
Sergio Vera Avatar asked Nov 19 '14 14:11

Sergio Vera


People also ask

How do I SELECT data from one table is not in another table?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

Can we use SELECT * with GROUP BY?

You can use a SELECT command with a GROUP BY clause to group all rows that have identical values in a specified column or combination of columns, into a single row.

How does minus operator work in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

Can exists BE USED IN subquery?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.


2 Answers

You're just missing a filter:

SELECT a.*
FROM A as a
LEFT JOIN B AS b ON b.column = a.column
WHERE B.column IS NULL
like image 103
Dan Avatar answered Sep 29 '22 19:09

Dan


If B could have multiple rows that match A, then this query would be more appropriate:

SELECT a.*
FROM A as a
WHERE NOT EXISTS(SELECT NULL FROM B WHERE b.column = a.column)
like image 26
D Stanley Avatar answered Sep 29 '22 18:09

D Stanley