mysql - SQL select first found value in 'in group' -
is possible select first row matched in list?
table bar
: column 'bar' values: value2, value3
select * `foo` `bar` in ('value','value2','value3');
it select value2 , returns.
thanks in advance
edit:
the values expecting are:
foo foobar foobarsome foobarsomething
i determine based on length of strings need default value if nothing found. lets 'nothing' nothing bigger foobar , valid value.
you can use case statement in order clause specify order based on column values. use can use limit select 1 row in result.
select * foo bar in ('value','value1','value2') order case bar when 'value' 1 when 'value1' 2 when 'value2' 3 else 100 end limit 1;
i tested example on sql fiddle.
update: original poster edited question , added wants sort on string length , have default value of 'nothing' returned if there no results.
select * foo bar in ('value','value1','value2') order case bar when 'value' 1 when 'value1' 2 when 'value2' 3 else 100 end limit 1; select bar ( select bar, 0 sortorder foo bar in ('value','value1','value2') union select 'nothing' bar, 999 sortorder ) x order sortorder, length(bar) limit 1;
you can see update query run in sql fiddler.
this solution works using union combine default value of 'nothing' result , includes "sortorder" column. union'ed queries order sortorder column default value sorted bottom of results, results sorted length of bar. there limit 1 clause default value 'nothing' appear in final result if record otherwise shortest string matches in 'in group' set returned.
Comments
Post a Comment