我认为标题有点模糊。我将在下面解释。 所以我有这些表
约会表
id created_by created_by_id
---------------------------
1 provider 10
2 customer 5
3 admin 1
提供者表
id first_name last_name
------------------------
.. ... ...
10 x y
客户表
id first_name last_name
-------------------------
.. ... ...
5 a b
管理员表
id first_name last_name
--------------------------
.. ... ...
1 c d
我想根据created_by字段查询并返回相关帐户的全名,因此如果是提供者,则查询提供者表中的名称,依此类推。
我试过这个
select *,
(
SELECT
CASE
WHEN appointments.created_by='provider' THEN
CONCAT(d.first_name, " ", d.last_name)
WHEN appointments.created_by='customer' THEN
CONCAT(p.first_name, " ", p.last_name)
ELSE CONCAT(p.first_name, " ", p.last_name)
END
FROM providers as d, customers as p
WHERE
appointments.created_by_id = (CASE
WHEN appointments.created_by='provider' THEN
d.id
WHEN appointments.created_by='customer' THEN
p.id
ELSE p.id
END)
)
from appointments
但它似乎不起作用。 你能帮我一个像这样的表吗?
id created_by name
-------------------
1 provider x y
2 customer a b
3 admin c d
答案 0 :(得分:1)
select *,
case appointments.created_by
when 'admin' then (select concat(first_name, ' ', last_name) from admins where admins.id = appointments.created_by_id)
when 'customer' then (select concat(first_name, ' ', last_name) from customers where customers.id=appointments.created_by_id)
when 'provider' then (select concat(first_name, ' ', last_name) from providers where providers.id = appointments.created_by_id)
END as name
from appointments
这是一个带有案例方法的sqlfiddle:http://sqlfiddle.com/#!9/43510/1