gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:06:32 26 4
gpt4 key购买 nike

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

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

用到的三个表:

“团队”:

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 | /

“ session ”:

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

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

从寄存器中选择所有结果,按用户分组,并按 session 开始时间排序。但是,如果注册表中没有标记,我希望它显示“-”(如果需要可以通过 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,
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

最佳答案

MySQL 不支持

Full outer join。至少到5.6版本,可以查看MySQL Join doc . cross join 可能是一种解决方法:

已编辑

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

关于php - MySQL FULL JOIN 一个表,并在同一个查询中 LEFT JOIN 另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9444397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com