简体   繁体   中英

How to get distinct rows from SQL

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

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

I have modified the srini.venigalla answer. Thanks to him.

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

Try to get multiple rows from table

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM