简体   繁体   中英

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.

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

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