我的数据库结构如下:
id name gender
1 abc male
2 xyz female
id name
1 maths
2 science
3 english
id st_id sub_id marks
1 1 1 20
2 1 2 30
3 2 1 40
我想要这样的结果:
name subjects marks
abc maths 20
abc science 30
xyz maths 40
abc english 0
xyz science 0
xyz english 0
单独使用MySQL查询是否可以实现上述结果?
我尝试了这个查询:
SELECT *
FROM students
LEFT JOIN studentmarks
ON studentmarks.std_id = students.id
LEFT JOIN subjects
ON subjects.id = studentmarks.sub_id
结果不是我想要的,因为我使用join
因此它只会返回匹配的id
。
答案 0 :(得分:1)
这可能有用
SELECT cr.st_name, cr.sub_name, COALESCE(c.marks, 0)
FROM (SELECT a.id st_id,
a.NAME st_name,
b.NAME sub_name,
b.id sub_id
FROM students a,
subjects b) cr
LEFT JOIN studentmarks c
ON cr.sub_id = c.sub_id
AND c.st_id = cr.st_id
答案 1 :(得分:0)
您可以使用以下查询
来实现结果SELECT SM.marks,
S.NAME AS Student_name,
SBJ.NAME as Subject
FROM studentmarks AS SM
JOIN students AS S ON SM.st_id = S.id
JOIN subjects AS SBJ ON SM.sub_id = SBJ.id
你也可以使用CROSS加入,我想如果你想坚持你当前的查询
答案 2 :(得分:0)
试一下
SELECT A.name, B.name, C.marks
FROM students A, subjects B, studentmarks C
WHERE A.id = C.st_id AND B.id = C.sub_id;