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".
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.
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.
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.
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.
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
You can use IN
, but it's super inefficient:
SELECT * FROM tableA WHERE id NOT IN (SELECT id FROM tableB)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With