高效的短SQL查询

时间:2018-06-18 19:20:24

标签: mysql

我有这张桌子叫论文

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

我希望结果

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

我试过了

$sql = "SELECT DISTINCT (MAX(Paper_Code) 
     FROM papers WHERE Subject_Code = (SELECT DISTINCT Subject_Code))";

我是sql的新手,尝试了很多次但是一直都失败了。

1 个答案:

答案 0 :(得分:0)

select a.* from yourtable a join (
select subject_code, max(id)id
from yourtable
group by subject_code) b 
on a.subject_code=b.subject_code and a.id=b.id