Select * Where not Exists gives me errors
-
23-04-2021 - |
Question
Ok my objective is to query table 1 for data, but make sure that the data has not already been presented by checking in table 2.
Each data has an ID which is under the UUID column.
Select * FROM table1 Where Not Exists
(SELECT * FROM table2 WHERE table2.UUID = table1.UUID);
But I have researched and I have tried every possible way to write that query and I keep getting:
"ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT * FROM table2 WHERE table2.UUID = table1.UUID) at line 1"
Any help?
Also some of the articles I found on the internet suggest that a join would be more efficient, but others state that where not exists is better. Which is the more efficient route?
Thanks
Solution
i think you have to that like this:
SELECT UUID, ...
FROM Table1
WHERE UUID NOT IN
(SELECT UUID FROM Table2 WHERE Table2.UUID = Table1.UUID)
this means that the query selects all records from table1 where UUID
in table1 does not exist in table2
OTHER TIPS
Try replacing table
with table1
:
SELECT * FROM table1 WHERE NOT EXISTS (SELECT * FROM table2 WHERE table2.UUID = table1.UUID);
You could always use a LEFT JOIN
and check for NULL
instead.
SELECT a.*
FROM table1 AS a
LEFT JOIN table2 AS b ON a.UUID=b.UUID
WHERE b.UUID IS NULL