2015-10-14 61 views
3

我有一個有大量行(> 10K)的表。大多數行具有與ques_id關聯的重複角色值。我是新來的SQL。 我想要做的是按不同的最新ques_id選擇行。 這是我的表(tbl_questions)結構。SQL從表中選擇不同的最後一個值

id | ques_id | question  | ans 
1 | 2  | HTML stands.. | 3 
2 | 5  | PHP stands.. | 2 
3 | 6  | CSS stands.. | 4 
4 | 6  | CSS stands.. | 4 
5 | 5  | PHP stands.. | 2 
6 | 6  | CSS stands.. | 4 

這將是理想的結果:

id | ques_id | question  | ans 
1 | 2  | HTML stands.. | 3 
5 | 5  | PHP stands.. | 2 
6 | 6  | CSS stands.. | 4 

下面是到目前爲止,我已經試過查詢:

SELECT DISTINCT ques_id, question, ans FROM tbl_questions 

回答

1

希望爲每個question最新行?由集團給行號

SELECT ques_id, question, ans 
FROM tbl_questions t1 
where not exists (select 1 from tbl_questions t2 
        where t2.ques_id = t1.ques_id 
        and t2.id > t1.id) 
3

只是一個其他視角:您可以使用NOT EXISTS返回的行。

查詢

select t1.id, t1.ques_id, t1.question, t1.ans from 
(
    select id, ques_id, question, ans, 
    (
     case ques_id when @curA 
     then @curRow := @curRow + 1 
     else @curRow := 1 and @curA := ques_id end 
    ) as rn 
    from tbl_questions t, 
    (select @curRow := 0, @curA := '') r 
    order by ques_id,id desc 
)t1 
where t1.rn = 1; 

SQL Fiddle

+0

這不是「只是另一個角度」。這實際上可能會超越我自己的解決方案! – Strawberry

1
SELECT a.* 
    FROM tbl_questions a 
    JOIN 
    (SELECT ques_id 
      , MAX(id) max_id 
     FROM tbl_questions 
     GROUP 
      BY ques_id 
    ) b 
    ON b.max_id = a.id; 
+0

@ b0s3我並不是建議你刪除你的答案! – Strawberry

0

嘗試此查詢

SELECT 
SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id DESC),',',1) AS i_d, 
ques_id, 
question, 
SUBSTRING_INDEX(GROUP_CONCAT(ans ORDER BY id DESC),',',1) AS Answer 
FROM tbl_questions 
GROUP BY ques_id 

輸出

i_d |ques_id | question  | Answer 
1 2  HTML stands..  3 
5 5  PHP stands..  2 
6 6  CSS stands..  4 
+0

這是否解決了您的問題? –

+0

@Strawberry:謝謝指出。我編輯了我的代碼。請檢查一下 –

相關問題