统一这两个使用3个表的查询

时间:2012-07-24 13:37:49

标签: mysql sql query-optimization multiple-tables

我正在使用群组和群组成员资格功能

相关表格是:

  

usuarios(id,first_name,last_name,...)

     

groups(id,name,..,id_user)

     

group_members(id,id_group,id_user)

使用此设计我需要从groups表中获取创建者(groups.id_user是创建者)和group_members(group_members.id_usuario)中的成员

现在我只能通过2个查询来实现:

/* Retrieve members */
$q = 'SELECT usuarios.id as uid, usuarios.avatar, usuarios.first_name,usuarios.last_name 
                  FROM usuarios LEFT JOIN group_members ON usuarios.id = group_members.id_user
                  WHERE group_members.id_group = '.$this->id.'';
$r =  cache_query($q,'',10);
/* Retrive creator */           
$q2 = 'SELECT usuarios.id as uid, usuarios.avatar, usuarios.first_name,usuarios.last_name
                   FROM usuarios LEFT JOIN groups ON usuarios.id = groups.id_user
                   WHERE groups.id = '.$this->id;
$r2 =  cache_query($q2,'',10);

有没有办法通过一个查询实现它? (我还想把创建者作为成员插入,只使用第一个查询)

2 个答案:

答案 0 :(得分:3)

如果您加入usuarios表两次,那么您可以同时获取成员和组创建者信息:

select u.id as uid,
    u.avatar,
    u.first_name,
    u.last_name,
    uc.id as creator_uid,
    uc.avatar as creator_avatar,
    uc.first_name as creator_first_name,
    uc.last_name as creator_last_name
from groups g
inner join group_members gm on g.id = gm.id_group
left outer join usuarios u on gm.id_user = u.id
left outer join usuarios uc on g.id_user = uc.id
where g.id = ...

答案 1 :(得分:0)

您需要合并两个查询并在OR子句中添加WHERE条件:

SELECT usuarios.id as uid, usuarios.avatar, usuarios.first_name,usuarios.last_name
FROM usuarios
     LEFT JOIN group_members
        ON usuarios.id = group_members.id_user
     LEFT JOIN groups
        ON usuarios.id = groups.id_user
WHERE (group_members.id_group =  '.$this->id.' OR groups.id = '.$this->id)