我有一个表,其中包含match
的列表:
id | datetime
2864049 2019-04-03 00:00:00
2864050 2019-04-03 00:00:00
2864051 2019-04-03 00:00:00
基本上,我必须检查它是否存在以及是否需要更新,为此,我这样做了:
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
问题在于此查询不应返回任何结果,因为所有三个match
都存在,并且datetime
字段等于{{ 1}}表。
仅当matches
不同或mm
不存在时,查询才需要返回结果。
我做错了什么?
答案 0 :(得分:1)
将其他日期移至where子句
实时测试: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
输出:
| id | datetime |
|---------|----------------------|
| 2864052 | 2019-04-03T00:00:00Z |
| 2864053 | 2019-04-03T00:00:00Z |
2864052出现了,尽管它具有匹配的ID,因为它的日期时间与mm的日期时间不同
2864053出现,因为它不存在于毫米上
答案 1 :(得分:0)
尝试不使用强制转换,而是使用STR_TO_DATE转换日期
SELECT mm.match_id
FROM (SELECT 2864049 as match_id, str_to_date("2019-04-03 00:00:00", '%Y-%m-%d %T' ) AS match_datetime
UNION ALL
SELECT 2864050 , str_to_date("2019-04-03 00:00:00", '%Y-%m-%d %T' )
UNION ALL
SELECT 2864051 , str_to_date("2019-04-03 00:00:00", '%Y-%m-%d %T' )
) mm
LEFT JOIN `match` m on m.id = mm.match_id AND m.datetime <> mm.match_datetime
WHERE m.id IS NULL
但是您应该检查一下逻辑,因为您正在寻找不匹配的值的左连接...因此,如果mm表中的行与m表中的行不匹配,则所有这些行都有结果ID为null可能是您需要左连接来匹配行,例如:
SELECT mm.match_id
FROM (SELECT 2864049 as match_id, str_to_date("2019-04-03 00:00:00", '%Y-%m-%d %T' ) AS match_datetime
UNION ALL
SELECT 2864050 , str_to_date("2019-04-03 00:00:00", '%Y-%m-%d %T' )
UNION ALL
SELECT 2864051 , str_to_date("2019-04-03 00:00:00", '%Y-%m-%d %T' )
) mm
LEFT JOIN `match` m on m.id = mm.match_id AND m.datetime = mm.match_datetime
WHERE m.id IS NULL