MySQL FULL JOIN一个表,并在同一个查询中LEFT JOIN另一个表?

时间:2012-02-25 13:26:57

标签: php mysql join

我想在这一个查询中链接三个表。

该脚本是一个出勤登记簿,因此它为每个用户记录每次会议的出勤标记。

使用的三个表:

“团队”:

id | fullname | position         | class | hidden
1  | Team     | --               | black | 1
2  | Dan S    | Team Manager     | green | 0
3  | Harry P  | Graphic Engineer | blue  | 0

“寄存器”:

id | mid | uid | mark
1  | 1   | 2   | /
2  | 1   | 3   | I
3  | 2   | 1   | /
4  | 2   | 3   | /

“会议”:

id | maintask            | starttime  | endtime
1  | Organise Year Ahead | 1330007400 | 1330012800
2  | Gather Ideas        | 1330612200 | 1330617600
3  | TODO                | 1331217000 | 1331222400

有一个数据样本。我想做的是:

从寄存器中选择所有结果,由用户对它们进行分组,然后按会议开始时间对它们进行排序。但是,如果寄存器表中没有标记,我希望它显示“ - ”(如果需要可以通过php完成)所以预期的结果是这样的:

fullname | mark | mid
Dan S    | /    | 1
Dan S    | /    | 2
Dan S    | -    | 3
Harry P  | I    | 1
Harry P  | /    | 2
Harry P  | -    | 3

我的SQL查询目前是这样的:

  

SELECT u。fullname,u。id,r。mark,r。mid FROM team u FULL JOIN register r ON r。uid = u。id LEFT JOIN meetings m ON   r。mid = m。id GROUP BY u。id ORDER BY m。starttime ASC

我从MySQL收到错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'FULL JOIN register r ON r。uid = u。id LEFT JOIN meetings m   ON r。mid = m .id'在第1行

但是,我无法看到它的问题:S

请有人帮忙,指出正确的方向或给我一个可能的解决方案。非常赞赏

答案: 查询有效:

   SELECT     
       u.fullname,    u.id as uid,    
       if(r.uid = u.id, r.mark, '-') as mark,    
       if(r.uid = u.id, r.mid, '-') as mid,    
       r.mid,    m.starttime 
   FROM     
       team u 
         CROSS JOIN     
       register r ON u.id = r.uid
         LEFT OUTER JOIN     
       meetings m ON r.mid = m.id  
   WHERE    
       u.hidden = 0 
   GROUP BY     
       u.id, r.mid 
   ORDER BY     
       m.starttime, u.id ASC

1 个答案:

答案 0 :(得分:4)

MySQL不支持

Full outer join。至少在5.6版本中,您可以查看MySQL Join doccross join可能是一种解决方法:

<强> EDITED

SELECT 
   UxM.fullname,
   r.mark,
   UxM.mid,
   UxM.starttime
FROM 
   ( select u.id as uid, m.id as mid, u.fullname, m.starttime
     from
     team  u
      CROSS JOIN   
     meetings ) UxM
   left join
   register r
      on UxM.uid = r.uid and UxM.mid = r.mid
ORDER BY 
   UxM.starttime ASC

如果这可以解决您的问题,请告诉我。


简化:

SELECT     
    u.fullname,
    u.id AS uid,    
    COALESCE(r.mark, '-') AS mark,    
    COALESCE(r.mid, '-') AS mid,    
    m.id,
    m.starttime 
FROM     
    team u 
      CROSS JOIN     
    meetings m 
      LEFT JOIN     
    register r
        ON   r.mid = m.id  
        AND  r.id = u.uid
WHERE    
    u.hidden = 0 
GROUP BY     
    m.id, u.id 
ORDER BY     
    m.starttime, u.id