我如何在SQL中按ID筛选出三个表

时间:2016-03-23 13:27:07

标签: mysql sql

我的数据库中有这些表

table1                    table2                          table3
---------------          ----------------------------          ---------------------
NO.    courses           NO.   id        courses    grade          NO.       courses
---------------          -----------------------------         ---------------------
1      CHEM 101          1    2255      CHEM 101    A+             2         English    
2      ENGL 101          2    2255      English     A
3      MATH 101          1    2244      CHEM 101    A+

我编写了SQL查询来检索前面表格中的数据,以便向我显示这样的表格

----------------------------------------
course     grade     equal of my courses
----------------------------------------
CHEM 101   A+            null
ENGL 101   A             English   
MATH 101   null          null

查询

SELECT t1.courses,t2.grade,t3.courses AS 'equal of my courses'
FROM table1 t1
LEFT JOIN table2 t2
ON t1.NO = t2.NO
LEFT JOIN table3 t3
ON t2.NO = t3.NO;

它运行正常,但我如何按ID过滤掉?

1 个答案:

答案 0 :(得分:0)

使用where子句。将1替换为您要过滤的ID。

SELECT t1.courses,t2.grade,t3.courses AS 'equal of my courses'
FROM table1 t1
LEFT JOIN table2 t2
ON t1.NO = t2.NO
LEFT JOIN table3 t3
ON t2.NO = t3.NO
WHERE t2.id = 1;