简体   繁体   中英

Join tables using column value as table name

I've read many questions about joining tables where the column value is used as a table name but I do not know how to implement it on my case.

I have multiple tables. First Table is user .

    id   |  user_id  |  user_role
    1    |     1     |   admin
    2    |     2     |   manager
    3    |     3     |  employee

Second table is admin .

    id    |   fname  |  lname
    1     |   A1     |    J
    2     |   A2     |    C
    3     |   A3     |    S

Third table is manager .

    id      |   fname  |  lname
    1       |   M1     |    J
    2       |   M2     |    C
    3       |   M3     |    S

Third table is employee .

    id       |   fname  |  lname
    1        |   E1     |    J
    2        |   E2     |    C
    3        |   E3     |    S

How can I make it something like this:

SELECT * FROM user u INNER JOIN user.user_role ur ON ur.id = u.user_id

So it would yield something likes

u.id | u.user_id | u.user_role | ur.id |  ur.fname | ur.lname
 1   |    1      |   admin     |   1   |     A1    |    J
 2   |    2      |  manager    |   2   |     M2    |    C
 3   |    3      |  employee   |   3   |     E3    |    S

You could use UNION ALL for this:

SELECT      * 
FROM        user u
INNER JOIN  (   SELECT   'admin' as user_role, id, fname, lname 
                FROM     admin
                UNION ALL
                SELECT   'manager' as user_role, id, fname, lname
                FROM     manager
                UNION ALL
                SELECT   'employee' as user_role, id, fname, lname 
                FROM     employee
            ) ur
         ON ur.id = u.user_id
        AND ur.user_role = u.user_role

Here is working SQL fiddle .

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