SQL按最大列和内部联接排序多个表

时间:2018-06-21 16:35:24

标签: mysql sql

我有2张桌子

Papers

|ID | Paper_Code | Subject_Code |
| 0 | 2018/Eng/01|     ENG      |
| 1 | 2018/Eng/02|     ENG      |
| 2 | 2018/CS/01 |     CS       |
| 3 | 2018/Sci/01|     Sci      |
| 4 | 2018/Eng/03|     ENG      |

Subjects

|Subject_Code|Subject_Name|
|ENG         |English     |
|Sci         |Science     |
|CS          |Computers   |

我获得了下表,该表仅使用此SQL CODE显示每个不同主题代码的最大Paper_Code。

$sql = "SELECT Paper_Code FROM papers
       WHERE(Subject_Code,Paper_Code)
       IN(SELECT Subject_Code,MAX(Paper_Code)
       FROM Papers GROUP BY Subject_Code)
        ";

|ID | Paper_Code | Subject_Code |
| 4 | 2018/Eng/03|     ENG      |
| 2 | 2018/CS/01 |     CS       |
| 3 | 2018/Sci/01|     Sci      |

Now I want to INNER JOIN The Subjects Table to give me results like this

|ID | Paper_Code | Subject_Code | Subject_Name |
| 4 | 2018/Eng/03|     ENG      | English      |
| 2 | 2018/CS/01 |     CS       | Computers    |
| 3 | 2018/Sci/01|     Sci      | Science      |

我已经尝试过但是失败了

$sql = "SELECT Paper_Code FROM Papers
       WHERE(Subject_Code,Paper_Code)
       IN(SELECT Subject_Code,MAX(Paper_Code)
       FROM Papers GROUP BY Subject_Code)
       INNER JOIN Subjects
       ON Papers.Subject_Code = Subjects.Subject_Code";

1 个答案:

答案 0 :(得分:0)

JOINWHERE之前:

编辑:正如Barmar的评论所述,限定所有列:

SELECT p.Paper_Code
FROM Papers p
INNER JOIN Subjects s
    ON p.Subject_Code = s.Subject_Code
WHERE (p.Subject_Code, p.Paper_Code)
   IN (SELECT p2.Subject_Code, MAX(p2.Paper_Code)
       FROM Papers p2
       GROUP BY p2.Subject_Code)