簡體   English   中英

如何從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

首先找到Max版本,然后獲取它的數據:

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

我修改了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;

嘗試從表中獲取多行

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM