2011-09-03 95 views
2

我有4个表:一个与事件,一个与事件服务员,以及包含有关这些人员信息的两个人,他们可能是单一的个人或团体。数据库的设计看起来很公平,对吧?SQL查询从变量表

然后我需要得到谁将参加特定事件的名称。然后,我会使用常规连接获得类型的事件服务人员,以及其ID。但我还需要服务员'名称,并根据类型服务员是什么存储在两个不同的表中。

看一看我做了什么:

SELECT 
    ep.type_attendant 'type', 
    ep.id_attendant 'id', 
    IF(ep.type_attendant = 'user', CONCAT(u.firstname, ' ', u.lastname), g.name) 'fullname' 
FROM 
    events_attendants ep, 
    events e, 
    users u, 
    groups g 
WHERE 
    ep.id_event = e.id AND 
    ep.id_attendant = IF(ep.type_attendant = 'user', u.id, g.id) 

这样的作品,但因为它返回表格重复行是不完美的。 我想用什么来最终是类似的东西:(除了一个低于不工作)

SELECT 
    ep.type_attendant 'type', 
    ep.id_attendant 'id', 
    IF(ep.type_attendant = 'user', CONCAT(u.firstname, ' ', u.lastname), g.name) 'fullname' 
FROM 
    events_attendants ep, 
    events e, 
    IF(ep.type_attendant = 'user', users u, groups g) -- variable table 
WHERE 
    ep.id_event = e.id AND 
    ep.id_attendant = IF(ep.type_attendant = 'user', u.id, g.id) 

我还可以运行两个查询,并用PHP合并他们的结果,但我那种喜欢学习的人。

MySQL数据库btw。谢谢你的帮助!

+0

你有两个选择 - 一个'IF'打出了两个查询,或动态SQL ... –

+0

@OMG我最好骑小马:/ – Pioul

+0

如果'users'和'groups'表没有共同的'id',那么你也可以使用'UNION' - 没有任何'IF'。 –

回答

1
SELECT 
     ep.type_attendant AS `type`, 
     ep.id_attendant AS id, 
     CONCAT(u.firstname, ' ', u.lastname) AS fullname 
    FROM 
     events_attendants ep 
     JOIN 
     events e ON ep.id_event = e.id 
     JOIN 
     users u  ON ep.id_attendant = u.id 
    WHERE 
     ep.type_attendant = 'user' 
UNION ALL 
    SELECT 
     ep.type_attendant, 
     ep.id_attendant, 
     g.name 
    FROM 
     events_attendants ep 
     JOIN 
     events e ON ep.id_event = e.id 
     JOIN 
     groups g ON ep.id_attendant = g.id 
    WHERE 
     ep.type_attendant <> 'user'