您可以通过加入并使用优先级来执行这种类型的查询:
select b.*,
(case when u.id is not null then u.fname else tu.fname end) as fname,
(case when u.id is not null then u.lname else tu.lname end) as lname
from booking b left outer join
user u
on b.user_id = u.id left outer join
tmp_user tu
on b.user_id = tu.id
您还可以将条件添加and u.uid is null
到第二个联接。我不知道这是否有助于或妨碍性能。
哦,如果你想要用户表的值,那么这只是对逻辑的一个小修改:
select b.*,
(case when b.user_table = 'user' then u.fname else tu.fname end) as fname,
(case when b.user_table = 'tmp_user' then u.lname else tu.lname end) as lname
from booking b left outer join
user u
on b.user_id = u.id left outer join
tmp_user tu
on b.user_id = tu.id;