我想知道这个查询是否正确。我试图选择最近日志条目的人(姓名/电子邮件)(如果该人从未登录过该事件,则为NULL),每个人在每天发布的事件少于前一天。以下是表约束:
我使用以下查询:
SELECT
max(`log`.`date_added`) AS `logdate`,
`log`.`description`,
`eventppl`.`staff_id`,
`staff`.`name`,
`staff`.`email`,
`event`.`name`,
`event`.`deleted`
FROM `events` AS `event`
LEFT JOIN `logs` AS `log` ON `log`.`event_id` = `event`.`event_id`
LEFT JOIN `events_people` AS `eventppl` ON `event`.`event_id` = `eventppl`.`event_id`
LEFT JOIN `staff` AS `staff` ON `eventppl`.`staff_id` = `staff`.`staff_id`
WHERE
`event`.`deleted` = 0 AND
`eventppl`.`date_left_event` = 0 AND
DATE(FROM_UNIXTIME(`log`.`date_added`)) <= DATE_SUB(CURDATE(), INTERVAL 1 DAY)
GROUP BY `event`.`name`
我有以下表结构:
日志
log_id | main_event_id | description | date | staff_id
1 1 log entry timestamp 11199
2 1 log entry timestamp 11199
3 1 log entry timestamp 11127
4 2 log entry timestamp 11199
5 2 log entry timestamp 11199
事件
event_id | name | deleted
1 EVENT_name1 0
2 Event_name2 0
3 Event_name3 1
events_people(11199)后来重新加入
event_id | staff_id | date_left_event
1 11199 234234234
1 11126 0
1 11125 0
1 11199 0
2 11199 0
3 11199 0
人员
staff_id | name | email
11125 john a@b.com
11126 jane a@bbasfd.com
答案 0 :(得分:1)
您的where
子句正在撤消left outer join
。如果没有匹配项,则第二个表的列中的值为NULL
,这会自动无法进行比较。
解决方案是将比较从where
移至on
:
FROM `events` AS `event`
LEFT JOIN `logs` AS `log`
ON `log`.`event_id` = `event`.`event_id` and
DATE(FROM_UNIXTIME(`log`.`date_added`)) <= DATE_SUB(CURDATE(), INTERVAL 1 DAY)
LEFT JOIN `events_people` AS `eventppl`
ON `event`.`event_id` = `eventppl`.`event_id` and `eventppl`.`date_left_event` = 0
LEFT JOIN `staff` AS `staff` ON `eventppl`.`staff_id` = `staff`.`staff_id`
WHERE `event`.`deleted` = 0
GROUP BY `event`.`name`