How to select from Db elements from one table which do not have connected elements with certain property
I have tow tables in my MySQL database - one with flights and one with tickets. Relation between flight and ticket is one to many. I want to delete all flights for which there are no tickets or they are canceled. How to do this with one SQL statement.
What I have now:
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());
This statement does not take in account flights for which exist both canceled and not canceled tickets. So I should correct it, but I have no idea how to do开发者_StackOverflow中文版 this in one statement.
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))
精彩评论