每种类型选择表?

时间:2019-03-14 16:24:34

标签: mysql sql phpmyadmin

我在通过帐户表中的user_ID选择不同的user_details表时遇到问题,


帐户表

+---------+------------+---------------+------------+
| user_ID | user_Name  | user_Password | user_Level |
+---------+------------+---------------+------------+
| 1       | student    | student       | 1          |
| 2       | instructor | instructor    | 2          |
| 3       | admin      | admin         | 3          |
+---------+------------+---------------+------------+

学生详细信息

+---------+----------+--------------+
| stud_ID | user_ID  | stud_details |
+---------+----------+--------------+
| 1       | 1        | student      |
| 2       | null     | student2     |
| 3       | null     | student3     |
+---------+----------+--------------+

教师详细信息

+---------+---------+--------------+
| inst_ID | user_ID | inst_details |
+---------+---------+--------------+
| 1       | null    | instructor   |
| 2       | 2       | instructor2  |
| 3       | null    | instructor3  |
+---------+---------+--------------+

Admin_details 与上方的详细信息表相同。.

这是我的示例查询:

SELECT 
ua.user_ID,
ul.level_Name,
ua.user_Name,
ua.user_status,
(CASE
    WHEN ua.level_ID = 1 THEN (SELECT * FROM `record_student_details` rsd WHERE rsd.user_ID = ua.user_ID)
    WHEN ua.level_ID = 2 THEN "2"
    WHEN ua.level_ID = 3 THEN "3"
    ELSE "error"
END) as ulvl FROM `user_accounts` ua
LEFT JOIN user_level ul ON ua.level_ID = ul.level_ID

我想要的结果是这样的,如果user_level为1,则用户详细信息必须来自student_details,然后,如果user_level为2,则他的详细信息将为教师的详细信息,然后,如果user_level为3,则来自admin_details的详细信息

+---------+------------+---------------+------------+--------------------+
| user_ID | user_Name  | user_Password | user_Level | details            |
+---------+------------+---------------+------------+--------------------+
| 1       | student    | student       | 1          | Student_details    |
| 2       | instructor | instructor    | 2          | Instructor_details |
| 3       | admin      | admin         | 3          | Admin_details      |
+---------+------------+---------------+------------+--------------------+

1 个答案:

答案 0 :(得分:2)

您似乎想要这样的东西:

SELECT ua.user_ID, ul.level_Name, ua.user_Name, ua.user_status,
       COALESCE(stud_id, inst_id) as id,
       COALESCE(stud_details, inst_details) as details
FROM user_accounts ua LEFT JOIN
     user_level ul
     ON ua.level_ID = ul.level_ID LEFT JOIN
     student_details sd
     ON sd.user_ID = ua.user_ID AND ua.level_ID = 1 LEFT JOIN
     student_details sd
     ON id.user_ID = ua.user_ID AND ua.level_ID = 2