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

前端之家收集整理的这篇文章主要介绍了php – MySQL FULL JOIN一个表,并在同一个查询中LEFT 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收到错误

You have an error in your sql Syntax; check the manual that
corresponds to your MysqL server version for the right Syntax to use
near ‘FULL JOIN register r ON r.uid=u.id LEFT JOIN meetings m
ON r.mid=m.`id’ at line 1

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

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

回答:
查询有效:

   SELECT     
       u.fullname,u.id as uid,if(r.uid = u.id,r.mark,'-') as mark,r.mid,'-') as 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
最佳答案
MysqL不支持全外连接.至少到5.6版,你可以检查MySQL Join doc.交叉连接可能是一种解决方法

EDITED

SELECT 
   UxM.fullname,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

猜你在找的MySQL相关文章