简体   繁体   中英

How to query data from one of two tables based on availablity

I have a query which joins multiple tables. For eg.

Select u.username,r.role,s.salary
from user u, roles r, salary s
where u.userid = s.userid
and r.roleid = u.roleid.

Now I need to append the condition to get the data only if the eligibility flag is true, which can be present in two tables (default eligibility and user eligility) . If the data is in user_eligiblity i need to check from user_eligility else i need to get from default eligibility.

Select u.username,r.role,s.salary
from user u, roles r, salary s, default_eligility de, user_eligiblity ue
where u.userid = s.userid
and r.roleid = u.roleid
and (if ue has data check if ue.eligible=y and ue.userid = u.userid 
     else get data from de.eligibity='y' and de.roleid = u.roleid)

User Eligibility may or may not have have rows for the user. If it does not have have to take it from default table.

The join replace your where condition

And the final left join is the one you want to find which user have a match in user_eligiblity the one who doesnt will get null

COALESCE will return ue.eligible if <> null or de.eligible otherwise

Select u.username, r.role, s.salary
from user u 
join roles r 
  on u.roleid = r.roleid
join salary s
  on u.userid = s.userid
join default_eligility de
  on u.roleid = de.roleid 
left join user_eligiblity ue
  on u.userid = ue.userid
WHERE
     COALESCE(ue.eligible, de.eligible) = 'y'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM