I'm attempting to get a list of values that don't exist in another table for a specific date.
Table Layouts:
table1 (TABLE)
id INT(10)
table2 (TABLE)
id INT(10)
table1id INT(10)
dateupdated DATETIME(19)
Query that I thought would work that isn't.
SELECT t1.id FROM Table1 as t1
JOIN Table2 as t2
ON t1.id=t2.table1id
WHERE date(t2.dateupdated) != DATE(NOW())
I'm expecting id 7 and 8 to come back from the above query, since they don't exist in Table2. But I'm getting no rows back.
Reversing the Query to match = DATE(NOW()) gives me the lines that do have matches
SELECT t1.id FROM Table1 as t1
JOIN Table2 as t2
ON t1.id=t2.table1id
WHERE date(t2.dateupdated) = DATE(NOW())
Response:
id
1
2
3
4
5
6
9
10
Any guidance would be appreciated, I'm still learning MySQL. But I'm missing something very simple here.
http://sqlfiddle.com/#!9/7a9fc/11
SELECT t1.id FROM Table1 as t1
LEFT JOIN Table2 as t2
ON t1.id=t2.table1id
AND date(t2.dateupdated) = DATE(NOW())
WHERE t2.id IS NULL;
Since there is always more than one way, another way is using the NOT IN operator with a subquery (since MySQL doesn't support MINUS).
SELECT t1.id FROM Table1 as t1
WHERE t1.id NOT IN
(SELECT t2.table1id FROM Table2 as t2
WHERE date(t2.dateupdated) = DATE(NOW()))
For DBMS that do support MINUS, you could do:
SELECT t1.id FROM Table1 as t1
MINUS
SELECT t2.table1id FROM Table2 as t2
WHERE date(t2.dateupdated) = DATE(NOW())
This is the way that I prefer to do it:
SELECT id FROM Table1
WHERE id not in (select table1id from Table2 where date(dateupdated) = date(NOW()))
Learning mysql I found this invaluable reference: http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
Hope you find it useful!
Since the JOIN doesn't retrieve NULL rows, you have to use a LEFT or RIGHT JOIN to deal with empty ROWS.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.