gpt4 book ai didi

mysql - 根据其他表选择数据

转载 作者:行者123 更新时间:2023-11-29 00:25:03 24 4
gpt4 key购买 nike

我仍然是数据库和 mysql 方面的新手,我想学习如何使用 JOIN。很抱歉,我只是不知道如何用语言表达这种情况。希望大家看了这些数据都能明白。这是带有记录的表格:

Table student 
student_id | student_name
-------------------------
1 Ana
2 Billy
3 Connor

Table comp
comp_id | subj_id | comp_name
--------------------------
1 24 Run
2 24 Swim
3 24 Jump
4 25 Eat

Table comp_mark
semester | subj_id | student_id | comp_id | mark
-------------------------------------------------
1 24 1 1 7
1 24 1 2 4
1 24 1 3 6
1 24 2 1 4
1 24 2 2 8
1 24 3 1 9

我期望从选择 comp_mark 表(更新)的查询中得到类似这样的结果:

student_name | semester | subject_id | comp_id  | mark
-------------------------------------------------------
Connor 1 24 1 9
Connor null 24 2 null
Connor null 24 3 null

有没有人可以帮我解决这个问题?非常感谢

更新

我试过这个(Guillaume Poussel 的查询)并按 student_name 订购:

 SELECT s.student_name, cm.semester, c.subj_id AS subject_id, c.comp_id, cm.mark
FROM student s
CROSS JOIN comp c
LEFT JOIN comp_mark cm ON s.student_id = cm.student_id
AND cm.subj_id = c.subj_id
AND cm.comp_id = c.comp_id
ORDER BY s.student_name

结果: enter image description here

最佳答案

试试这个:

SELECT s.student_name, cm.semester, c.subj_id AS subject_id, c.comp_id, cm.mark
FROM student s
CROSS JOIN comp c
LEFT JOIN comp_mark cm ON s.student_id = cm.student_id AND cm.subj_id = c.subj_id AND cm.comp_id = c.comp_id

关于mysql - 根据其他表选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19344158/

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