mysql - 等于此右连接的左连接是什么?

标签 mysql sql left-join right-join

先谢谢了。

我的右连接工作正常,但当我尝试将其更改为左连接时出现错误。

问题是从 score-student 表 SC 中的 student who has higher score in class1 than class2 中获取有关学生的所有信息。

学生(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

最佳答案

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

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;

关于mysql - 等于此右连接的左连接是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50058522/

相关文章:

mysql - 存储过程返回所有记录,但期望是mysql中的一条记录

mysql - 合并相似的 SQL 行

c# - 使用 Entity Framework 在运行时动态选择列

MYSQL按 "gaps"填充组

mysql - 在触发器内使用变量

mysql - InnoDB 表空间 ID 错误

MySQL 2 列不工作的百分比=NULL

mysql - 有没有其他方法可以在 Sql 中使用 Alias?

mysql - 如何优化left join的sql?

mysql - 无法从左连接获取记录 0 :m relationship table