SQL QUERY COMPLEX JOIN

时间:2017-09-26 08:18:46

标签: mysql sql select join

我有几张桌子,我想要输出

在MAHASISWA上的NAMA MAHASISWA上的NIM = MHS_MAKUL上的NIM_MHS其中(N_TUGAS ='C'和N_MID ='B')和NILAI_MAKUL上的ID_MHS_MAKUL = MHS_MAKUL上的ID

这里是表格和列的列表

MAHASISWA

NIM | NAMA

MHS_MAKUL

ID | NIM_MHS

NILAI_MAKUL

N_TUGAS | N_MID | ID_MHS_MAKUL

我试过用这个,但是给我输出“表'mahasiswa.nim'不存在”

SELECT mahasiswa.NAMA, mahasiswa.NIM, mhs_makul.ID, nilai_makul.NIM_MHS,
       nilai_makul.ID_mhs_makul
FROM mahasiswa
INNER JOIN mahasiswa.NIM ON mhs_makul.NIM_MHS
INNER JOIN mhs_makul.ID ON nilai_makul.ID_mhs_makul
WHERE nilai_makul.N_TUGAS = 'C' AND nilai_makul.N_MID = 'B';

4 个答案:

答案 0 :(得分:2)

请了解JOIN语法。

SELECT mahasiswa.NAMA, mahasiswa.NIM, mhs_makul.ID, nilai_makul.NIM_MHS, nilai_makul.ID_mhs_makul
FROM mahasiswa
INNER JOIN mhs_makul ON mhs_makul.NIM_MHS = mahasiswa.NIM
INNER JOIN nilai_makul ON nilai_makul.ID_mhs_makul = mhs_makul.ID
WHERE nilai_makul.N_TUGAS = 'C' AND nilai_makul.N_MID = 'B';

答案 1 :(得分:1)

您的语法不正确。 join子句需要引用一个表,然后on子句具有此表连接的条件:

SELECT     mahasiswa.NAMA,
           mahasiswa.NIM,
           mhs_makul.ID,
           nilai_makul.NIM_MHS,
           nilai_makul.ID_mhs_makul
FROM       mahasiswa
INNER JOIN mhs_makul ON mahasiswa.NIM = mhs_makul.NIM_MHS
INNER JOIN nilai_makul ON mhs_makul.ID = nilai_makul.ID_mhs_makul
WHERE      nilai_makul.N_TUGAS = 'C' AND
           nilai_makul.N_MID = 'B';

答案 2 :(得分:1)

连接条件写得不正确,试试这个

SELECT mahasiswa.NAMA, mahasiswa.NIM, mhs_makul.ID, nilai_makul.NIM_MHS, nilai_makul.ID_mhs_makul  
FROM mahasiswa  
INNER JOIN mhs_makul  
ON mhs_makul.NIM_MHS = mahasiswa.NIM   
INNER JOIN nilai_makul  
ON nilai_makul.ID_mhs_makul = mhs_makul.ID   
WHERE nilai_makul.N_TUGAS = 'C'   
AND nilai_makul.N_MID = 'B';  

答案 3 :(得分:0)

尝试以下查询:

SELECT mahasiswa.NAMA, mahasiswa.NIM, mhs_makul.ID, nilai_makul.NIM_MHS,
       nilai_makul.ID_mhs_makul
FROM mahasiswa
INNER JOIN mhs_makul ON mahasiswa.NIM = mhs_makul.NIM_MHS
INNER JOIN nilai_makul ON mhs_makul.ID = nilai_makul.ID_mhs_makul
WHERE nilai_makul.N_TUGAS = 'C' AND nilai_makul.N_MID = 'B';

1 JOIN的文档,这是它的定义方式:

table_reference [INNER | CROSS] JOIN table_factor [join_condition]

因此,您需要在JOIN中指定表名,在ON子句中指定列名