根据作为所有表的公共字段的值从不同表中获取数据

时间:2013-05-06 10:31:20

标签: sql cakephp

我有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表中获取名称,

2 个答案:

答案 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 JOINCOALESCE一起使用。像这样:

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;