mysql - Return row only if value doesn't exist -
i have 2 tables - reservation:
id | some_other_column ----+------------------ 1 | value 2 | value 3 | value and second table - reservation_log:
id | reservation_id | change_type ----+----------------+------------- 1 | 1 | create 2 | 2 | create 3 | 3 | create 4 | 1 | cancel 5 | 2 | cancel i need select reservations not cancelled (it id 3 in example). can select cancelled simple "where change_type = cancel" condition, i'm struggling not cancelled, since simple doesn't work here.
select * reservation id not in (select reservation_id reservation_log change_type = 'cancel') or:
select r.* reservation r left join reservation_log l on r.id = l.reservation_id , l.change_type = 'cancel' l.id null the first version more intuitive, think second version gets better performance (assuming have indexes on columns used in join).
the second version works because left join returns row rows in first table. when on condition succeeds, rows include columns second table, inner join. when condition fails, returned row contain null columns in second table. where l.id null test matches rows, finds rows don't have match between tables.
Comments
Post a Comment