Wednesday, 15 May 2013

sql - MYSQL Can WHERE IN default to ALL if no rows returned -



sql - MYSQL Can WHERE IN default to ALL if no rows returned -

have existing table of results this;

race_id race_num racer_id place 1 0 32 2 1 1 32 3 1 2 32 1 1 3 32 6 1 0 44 2 1 1 44 2 1 2 44 2 1 3 44 2 etc...

have lots of php scripts access table output results in nice format.

now have case need output results race_nums. have created table races_included.

race_view race_id race_num day 1 1 0 day 1 1 1 day 2 1 2 day 2 1 3

and can utilize query right results.

select racer_id, place results race_id=1 , race_num in (select race_num races_included race_id='1' , race_view='day 1')

this great need feature few races , have work in compatible mode simple case show races. need add together alot of rows races_included table. like

race_view race_id race_num 1 0 1 1 1 2 1 3

95% of races don't utilize daily feature.

so looking way alter query if race 1 there no records in races_included table defaults races. in add-on need close same execution speed query without in clause, because query or variations of used lot.

one way work redefine table races_excluded , utilize not in. works great pain manage table when races added or deleted.

is there simple way utilize exists , in in tandem subquery desired results? or other neat trick missing.

to clarify have found working slow solution.

select * race_results race_id=1 , find_in_set(race_num, (select if((select count(*) races_excluded rid=1>0),(select group_concat(rnum) races_excluded rid=1 , race_view='day 1' grouping rid),race_num)))

it checks if records exists race_id , if not homecoming set equal current race_num , if yes returns list of included race nums.

you can using or in subquery:

select racer_id, plac results race_id = 1 , race_num in (select race_num races_included race_id = '1' , (race_view = 'day 1' or raw_view = 'any') );

mysql sql subquery

No comments:

Post a Comment