sql - Improving my query efficiency - reducing full table scans? -
i wondering if me out have working query, feel not efficient be. ill go on explain:
i have car table , carevent table. car table stores info such make, model etc of car. carevent table stores events happened on car such car has been crashed or car has been fixed. if no status of "crashed" exists on carevent table given car has not been crashed. query return cars have been crashed not fixed. way have wrote requires 2 scans of carevent table.
what im wondering is, there more efficient way query?
my query follows:
select * car c (select count(ce.id) carevent ce car_id = c.id , ce.careventtype = 'crashed') > 0 , (select count(ce.id) carevent ce car_id = c.id , ce.careventtype = 'fixed') = 0
any advice appreciated.
oh, infamous count()
in subquery. want use exists
, not count
:
select c.* car c exists (select 1 carevent ce ce.car_id = c.id , ce.careventtype = 'crashed') , not exists (select 1 carevent ce ce.car_id = c.id , ce.careventtype = 'fixed');
for performance, want index on carevent(car_id, careventtype)
. also, sure use table aliases in correlated subqueries.
Comments
Post a Comment