![](/img/trans.png)
[英]MySQL query - join different tables based on a precondition (value retrieved from a different table)
[英]MySQL query from different tables based on a field of a table
我認為標題有點模糊。 我會在下面解釋。 所以我有這些桌子
約會表
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
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
這是一個帶有case方法的sqlfiddle: http ://sqlfiddle.com/#!9/43510/1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.