我有5张桌子..,
活动,用户,管理员,个人,雇主
Activity,Admin,Individual,Employer属于Users表,如图所示
Activity Admin Individual Employer
+-----------+ +------------------+ +------------------+ +------------------+
id | user_id id | user_id | name id | user_id | name id | user_id | name
+-----------+ +------------------+ +------------------+ +------------------+
现在,我正在Activity
表格
如果user_id
值在Admin
表中,那么我需要从Admin
表中获取名称,
如果user_id
值在Employer
表中,那么我需要从Employer
表中获取名称,
同样,如果user_id
值在Individual
表中,那么我需要从Individual
表中获取名称,
答案 0 :(得分:2)
尝试这个概念:
SELECT
A.ID AS ID
A.User_id AS UserID
A.Name AS Name
'Admin' AS TableName
FROM Admin A INNER JOIN Activity B
ON A.User_Id=B.User_Id
UNION ALL
SELECT
A.ID AS ID
A.User_id AS UserID
A.Name AS Name
'Individual' AS TableName
FROM Individual A INNER JOIN Activity B
ON A.User_Id=B.User_Id
UNION ALL
SELECT
A.ID AS ID
A.User_id AS UserID
A.Name AS Name
'Employer' AS TableName
FROM Employer A INNER JOIN Activity B
ON A.User_Id=B.User_Id
答案 1 :(得分:0)
将LEFT JOIN
与COALESCE
一起使用。像这样:
SELECT
a.id,
COALESCE(d.name, i.name, e.name) AS userName
FROM Activity AS a
LEFT JOIN admin AS d ON a.user_id = d.user_id
LEFT JOIN Individual AS i ON a.user_id = i.user_id
LEFT JOIN Employer AS e ON a.user_id = e.user_id;