如何从SQL获取不同的行

时间:2012-07-26 17:30:42

标签: php mysql sql codeigniter

这是我的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

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

我修改了srini.venigalla的答案。谢谢他。

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

答案 2 :(得分:0)

尝试从表中获取多行

$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()->result_array();
相关问题