我想列出未发送的通知。所以我尝试了如下查询。但是它显示了错误的结果。有什么方法可以显示未使用以下查询发送的通知。
SELECT
vtn.*,
vn.id as notice_id,
vn.vnotice_datetime as sent_notice_time
FROM
vtemplates vt
LEFT JOIN vtemplate_notices vtn ON( vtn.vtemplate_id = vt.id)
LEFT JOIN vnotices vn ON(vn.vtemplate_notice_id = vtn.id AND vn.vnotice_datetime IS nULL)
LEFT JOIN violations v ON ( v.vtemplate_id = vt.id)
WHERE
v.id = 1
Records in a violation_notices table are as follows:
--------------------------------------------------------------
id vtemplate_notice_id desc vnotice_datetime created_on
---------------------------------------------------------------
1 1 test1 22/12/2018 05:30 22/12/2018
预期结果:
id vtemplate_id created_on notice_id sent_notice_time
---------------------------------------------------------------
2 1 23/12/2018 NULL NULL
3 1 24/12/2018 NULL NULL
4 1 24/12/2018 NULL NULL
实际结果:
id vtemplate_id created_on notice_id sent_notice_time
---------------------------------------------------------------
1 1 22/12/2018 NULL NULL
2 1 23/12/2018 NULL NULL
3 1 24/12/2018 NULL NULL
4 1 24/12/2018 NULL NULL
在实际结果中,它显示的第一条记录(不应出现)的vnotice_datetime不是NULL,但仍在显示。
答案 0 :(得分:0)
您可以使用NOT EXISTS
或在IS NULL
子句中测试连接的列WHERE
https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html
例如
SELECT * FROM violations
WHERE NOT EXISTS(
SELECT * FROM notifications
WHERE violation_id = violations.id
)
SELECT v.*, n.* FROM violations v
LEFT JOIN notifications n
ON n.violation_id = v.id
WHERE n.violation_id IS NULL
答案 1 :(得分:0)
好吧,左联接不会删除不匹配的行。将IS NULL
从ON
移到WHERE
子句可能会起作用。
SELECT vtn.*,
vn.id notice_id,
vn.vnotice_datetime sent_notice_time
FROM vtemplates vt
LEFT JOIN vtemplate_notices vtn
ON vtn.vtemplate_id = vt.id
LEFT JOIN vnotices vn
ON vn.vtemplate_notice_id = vtn.id
LEFT JOIN violations v
ON v.vtemplate_id = vt.id
WHERE v.id = 1
AND vn.vnotice_datetime IS NULL;