Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from table A which does not exist in table B

Tags:

select

mysql

I am trying to compose a SELECT statement for MySQL which select from table A what does not exist in table B. For example:

Table A:

+------+
| BAND |
+------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
+------+

Table B:

+------+
| HATE |
+------+
| 1    |
| 5    |
+------+

So if table A is all bands, and table B is the bands I hate, then I only want bands I do NOT hate. So the result of a select should be:

+------+
| BAND |
+------+
| 2    |
| 3    |
| 4    |
+------+

How would I write a single select for this? Here was my last attempt:

SELECT * FROM A LEFT JOIN B ON A.BAND = B.HATE WHERE B.HATE IS NULL;

EDIT: The line above has been fixed! See comments below..."= NULL" versus "IS NULL".

like image 315
TSG Avatar asked Apr 08 '13 22:04

TSG


People also ask

Does not exist in SQL table?

SQL NOT EXISTS in a subquery In simple words, the subquery with NOT EXISTS checks every row from the outer query, returns TRUE or FALSE, and then sends the value to the outer query to use. In even simpler words, when you use SQL NOT EXISTS, the query returns all the rows that don't satisfy the EXISTS condition.

What does SELECT * from table mean?

An asterisk (" * ") can be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include: The FROM clause, which indicates the table(s) to retrieve data from.

How do I ignore duplicate records in SQL while selecting query?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

Does not exist in MySQL?

In MySQL, NOT EXISTS operator allows you to check non existence of any record in a subquery. The NOT EXISTS operator return true if the subquery returns zero row. The NOT EXISTS operator can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


2 Answers

I would use a join

select A.*
from A left join B on A.BAND = B.HATE
where B.HATE IS NULL;

Remember: Create the appropriate indexes for your table

like image 112
Barranka Avatar answered Sep 30 '22 17:09

Barranka


You can use IN, but it's super inefficient:

SELECT * FROM tableA WHERE id NOT IN (SELECT id FROM tableB)
like image 42
Stephen Fischer Avatar answered Sep 30 '22 17:09

Stephen Fischer