我的MySQL数据库中有两个表 - 一个有航班,一个有票。航班和机票之间的关系是一对多的。我想删除所有没有门票或取消的航班。如何使用一个SQL语句执行此操作。
我现在拥有的:
M('Db')->exec('
DELETE
f
FROM
flight f
LEFT JOIN
ticket p
ON
f.session_id = p.flight_session_id AND
f.id = p.flight_id
WHERE
f.cdate < ? AND
( p.is_canceled =1 OR p.id IS NULL )
', $this->getSweepTime());
此声明不考虑已存在已取消和未取消的票证的航班。所以我应该纠正它,但我不知道如何在一个声明中做到这一点。
答案 0 :(得分:1)
DELETE FROM Flight f
WHERE f.cdate < ?
AND
(NOT EXISTS (SELECT 1
FROM ticket t
WHERE f.session_id = p.flight_session_id
AND f.id = p.flight_id) OR EXISTS
(SELECT 1
FROM ticket t
WHERE f.session_id = t.flight_session_id
AND f.id = t.flight_id HAVING
SUM(Canceled) - COUNT(*) = 0))