2015-10-14 63 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:谢谢指出。我编辑了我的代码。请检查一下 –

相关问题