[英]MySQL query from different tables based on a field of a table
I think the title is a bit vague. 我认为标题有点模糊。 I'll explain below.
我会在下面解释。 So I have these tables
所以我有这些桌子
appointments table
约会表
id created_by created_by_id
---------------------------
1 provider 10
2 customer 5
3 admin 1
providers table
提供者表
id first_name last_name
------------------------
.. ... ...
10 x y
customers table
客户表
id first_name last_name
-------------------------
.. ... ...
5 a b
admins table
管理员表
id first_name last_name
--------------------------
.. ... ...
1 c d
I want to query and return full name of the relevant account based on created_by field, so if it is provider, it query the name in provider table, and so on. 我想基于created_by字段查询并返回相关帐户的全名,因此,如果它是提供者,它将在提供者表中查询名称,依此类推。
I have tried this 我已经试过了
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
But it doesn't seem to work. 但这似乎不起作用。 Could you please help me to achieve a table like this
你能帮我做成一张这样的桌子吗
id created_by name
-------------------
1 provider x y
2 customer a b
3 admin c d
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
Here is a sqlfiddle with the case method: http://sqlfiddle.com/#!9/43510/1 这是一个带有case方法的sqlfiddle: http ://sqlfiddle.com/#!9/43510/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.