I have a table which contains a list of match
:
id | datetime 2864049 2019-04-03 00:00:00 2864050 2019-04-03 00:00:00 2864051 2019-04-03 00:00:00
Essentially, I have to check if it exists and if it needs to be updated, for doing so I did:
SELECT mm.match_id FROM (SELECT 2864049 as match_id, CAST("2019-04-03 00:00:00" AS DATETIME) AS match_datetime UNION ALL SELECT 2864050 as match_id, CAST("2019-04-03 00:00:00" AS DATETIME) AS match_datetime UNION ALL SELECT 2864051 as match_id, CAST("2019-04-03 00:00:00" AS DATETIME) AS match_datetime ) mm LEFT JOIN `match` m on m.id = mm.match_id AND m.datetime <> mm.match_datetime WHERE m.id IS NULL
The problem is that this query shouldn’t return any result, because all the three match
exists, and also have the datetime
field equal to the matches
provided in the mm
table.
The query need to return a result only if the datetime
is different or if the match
doesn’t exist.
What I did wrong?
Advertisement
Answer
Move the different date to where clause
Live test: http://sqlfiddle.com/#!9/ee7ffb/1
CREATE TABLE `match` (`id` int, `datetime` datetime) ; INSERT INTO `match` (`id`, `datetime`) VALUES (2864049, '2019-04-03 00:00:00'), (2864050, '2019-04-03 00:00:00'), (2864051, '2019-04-03 00:00:00'), (2864052, '2019-04-03 00:00:00'), (2864053, '2019-04-03 00:00:00'), (2864054, '2019-04-03 00:00:00') ; SELECT m.id, `datetime` FROM `match` `m` left join (SELECT 2864049 as match_id, CAST("2019-04-03 00:00:00" AS DATETIME) AS match_datetime UNION ALL SELECT 2864050 as match_id, CAST("2019-04-03 00:00:00" AS DATETIME) AS match_datetime UNION ALL SELECT 2864051 as match_id, CAST("2019-04-03 00:00:00" AS DATETIME) AS match_datetime union all SELECT 2864052 as match_id, CAST("2019-04-04 00:00:00" AS DATETIME) AS match_datetime union all SELECT 2864054 as match_id, CAST("2019-04-03 00:00:00" AS DATETIME) AS match_datetime ) mm on m.id = mm.match_id WHERE mm.match_id IS NULL -- not existing or m.datetime <> mm.match_datetime -- move to where clause
Output:
| id | datetime | |---------|----------------------| | 2864052 | 2019-04-03T00:00:00Z | | 2864053 | 2019-04-03T00:00:00Z |
2864052 appears despite it has a matching id as its datetime is different from mm’s
2864053 appears as it is not existing on mm