如何从SQL获取不同的行(How to get distinct rows from SQL)

这是我的SQL表。 在这里,我希望得到所有

marks_table ID STUD_ID MARKS VERSION VERIFICATION_ID 1 50 90 1 2 2 22 50 1 2 3 33 20 1 2 4 10 30 1 2 5 55 50 1 2 6 55 40 2 2 7 20 60 1 2 8 30 90 1 2 9 10 88 1 3 10 10 45 2 3

我想要的是,通过verification_id得到所有结果,版本是更大的值。 例如,ID 5,6和9,10具有相同的stud_id,具有不同的标记,并且版本也不同。 我想获得最大版本结果以及来自该verification_id的所有其他结果。

在CodeIgniter中,我使用了以下命令。

$this->db->select('*'); $this->db->from('marks_table'); $this->db->where('version IN (SELECT MAX(version) FROM marks_table)',NULL,FALSE); $this->db->where('verification_id','2'); $this->db->get();

我得到的只是最终的最终版本

marks_table ID STUD_ID MARKS VERSION VERIFICATION_ID 6 55 40 2 2

我真正想要的是这样的

marks_table ID STUD_ID MARKS VERSION VERIFICATION_ID 1 50 90 1 2 2 22 50 1 2 3 33 20 1 2 4 10 30 1 2 6 55 40 2 2 7 20 60 1 2 8 30 90 1 2

This is my SQL table. here i want to get all

marks_table ID STUD_ID MARKS VERSION VERIFICATION_ID 1 50 90 1 2 2 22 50 1 2 3 33 20 1 2 4 10 30 1 2 5 55 50 1 2 6 55 40 2 2 7 20 60 1 2 8 30 90 1 2 9 10 88 1 3 10 10 45 2 3

What i want is, get all the result by verification_id and version is greater values. For example ID 5,6 and 9,10 have same stud_id with different marks and there version is also diferent. I want to get max version result and all other result from that verification_id.

In CodeIgniter i have used following commands.

$this->db->select('*'); $this->db->from('marks_table'); $this->db->where('version IN (SELECT MAX(version) FROM marks_table)',NULL,FALSE); $this->db->where('verification_id','2'); $this->db->get();

What i got is only final max version

marks_table ID STUD_ID MARKS VERSION VERIFICATION_ID 6 55 40 2 2

What i really want, like this

marks_table ID STUD_ID MARKS VERSION VERIFICATION_ID 1 50 90 1 2 2 22 50 1 2 3 33 20 1 2 4 10 30 1 2 6 55 40 2 2 7 20 60 1 2 8 30 90 1 2

最满意答案

首先找到Max版本,然后获取它的数据:

select * from marks_table a where version = (select max(version) from marks_table where stud_id = a.stud_id);

First find the Max version then fetch it's data:

select * from marks_table a where version = (select max(version) from marks_table where stud_id = a.stud_id);

更多推荐