Select from three table on condition basise in mysql -


i have 3 tables

1- sale

id    unit    ref  1    200    rm-s-2002  2    300    rm-s-2003 

2- rent

id     unit    ref  1      400    rm-r-2009  2      100    rm-r-2010 

fields structure of both table same,in ref middle s represent sale table , r represent rent table

3- details

id      list_ref  1        rm-r-2010 2        rm-s-2002 3        rm-s-2003 

the detail table contains ref of both tables(rent , sale).now want select unit if

if details.list_ref=rent.ref select rent.unit else select sale.unit.

here condition comes before select...how can used in query?

try

select d.id, d.list_ref, coalesce(s.unit, r.unit) unit   details d left join sale s      on d.list_ref = s.ref left join rent r     on d.list_ref = r.ref  

sample output:

 | id |  list_ref | unit | ------------------------- |  1 | rm-r-2010 |  100 | |  2 | rm-s-2002 |  200 | |  3 | rm-s-2003 |  300 | 

here sqlfiddle demo


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -