什么是左连接,等于这个右连接?

c86crjj0  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(317)

先谢谢你。
我有这个右连接工作得很好,但当我试图把它改成左连接,我得到了一个错误。
问题是从一个名为sc的学生成绩表中,从1班比2班成绩高的学生表中获得关于学生的所有信息。
学生(sid,sname,sage,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

8zzbczxx

8zzbczxx1#

通常,如果您有一个正确的连接查询:

SELECT select_statement
FROM table1 
RIGHT JOIN table2 
ON join_condition;

您只需将其更改为left join query,如下所示:

SELECT select_statement
FROM table2 
LEFT JOIN table1
ON join_condition;

对于您的情况,当您将查询更改为left join时,您更改了select\语句,它会出错。
只需将上述内容应用于您的查询:

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;
tgabmvqs

tgabmvqs2#

第一个有效的查询是:

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;

table 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;

有两个问题需要解决:
问题1: `Student.*` 未解析,因为from节没有任何引用。
问题2:表格 `r` 构造不正确。
解决这两个问题后,将生成第二个修改后的查询,该查询可以工作:

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;

相关问题