先谢谢。
我有正确的加入工作正常,但当我尝试将其更改为左连接时,我收到了错误。
问题是从表格中获得有关学生的所有信息,该学生在第1课中的成绩高于第2课,而不是来自名为SC的成绩 - 学生表。
学生(SID,SNAME,鼠尾草,SSEX)
SC(SID,CID,得分)
这是我正确的加入:
SELECT * FROM Student RIGHT JOIN (
SELECT t1.SId, class1, class2 FROM
(SELECT SId, score as class1 FROM sc WHERE sc.CId = '01')AS t1,
(SELECT SId, score AS class2 FROM sc WHERE sc.CId = '02')AS t2
WHERE t1.SId = t2.SId
AND t1.class1 > t2.class2
)r
ON Student.SId = r.SId;
然后我尝试了类似的事情:
SELECT t1.SId, class1, class2, Student.* FROM
(SELECT SId, score as class1 FROM sc WHERE sc.CId = '01')AS t1,
(SELECT SId, score AS class2 FROM sc WHERE sc.CId = '02')AS t2
WHERE t1.SId = t2.SId
AND t1.class1 > t2.class2
)r
LEFT JOIN Student
ON Student.SId = r.SId;
但它没有用。
我对SQL很新,希望你能解释一下。
我正在使用MySQL5.7
答案 0 :(得分:3)
通常,如果您有正确的联接查询:
SELECT select_statement
FROM table1
RIGHT JOIN table2
ON join_condition;
您只需将其更改为左连接查询,如下所示:
SELECT select_statement
FROM table2
LEFT JOIN table1
ON join_condition;
对于您的情况,当您将查询更改为左连接时,您更改了select_statement,这会导致错误。
只需将以上内容应用于您的查询:
SELECT *
FROM (
SELECT t1.SId, class1, class2
FROM
(SELECT SId, score as class1 FROM sc WHERE sc.CId = '01') AS t1,
(SELECT SId, score AS class2 FROM sc WHERE sc.CId = '02') AS t2
WHERE t1.SId = t2.SId
AND t1.class1 > t2.class2
) r
LEFT JOIN Student
ON Student.SId = r.SId;
答案 1 :(得分:0)
第一个有效的查询是:
SELECT * FROM Student RIGHT JOIN (
SELECT t1.SId, class1, class2 FROM
(SELECT SId, score as class1 FROM sc WHERE sc.CId = '01')AS t1,
(SELECT SId, score AS class2 FROM sc WHERE sc.CId = '02')AS t2
WHERE t1.SId = t2.SId
AND t1.class1 > t2.class2
)r
ON Student.SId = r.SId;
正在通过此子查询创建表r
:
SELECT t1.SId, class1, class2 FROM
(SELECT SId, score as class1 FROM sc WHERE sc.CId = '01')AS t1,
(SELECT SId, score AS class2 FROM sc WHERE sc.CId = '02')AS t2
WHERE t1.SId = t2.SId
AND t1.class1 > t2.class2
t1.Sid
,class1
和class2
的解析没有歧义。 t1.Sid
在r.Sid
加入Student.SId = r.Sid
时可用SELECT t1.SId, class1, class2, Student.* FROM
(SELECT SId, score as class1 FROM sc WHERE sc.CId = '01')AS t1,
(SELECT SId, score AS class2 FROM sc WHERE sc.CId = '02')AS t2
WHERE t1.SId = t2.SId
AND t1.class1 > t2.class2
)r
LEFT JOIN Student
ON Student.SId = r.SId;
。因此,查询有效。
导致问题的第二个查询在此处:
Student.*
有两个问题需要解决:
r
未解决,因为FROM部分没有任何引用。SELECT * from
(SELECT t1.SId, class1, class2 FROM
(SELECT SId, score as class1 FROM sc WHERE sc.CId = '01')AS t1,
(SELECT SId, score AS class2 FROM sc WHERE sc.CId = '02')AS t2
WHERE t1.SId = t2.SId
AND t1.class1 > t2.class2
)r
LEFT JOIN Student
ON Student.SId = r.SId;
未正确构建。解决后的两个问题会导致此修改后的第二个查询生效:
IsIncetiveAllowed