简体   繁体   English

SQL从表中选择不同的最后一个值

[英]SQL select distinct last values from table

I have a table that has a ton of rows (>10K). 我有一个有大量行(> 10K)的表。 Most of the rows have duplicate role values associated with the ques_id. 大多数行都具有与ques_id关联的重复角色值。 I'am new to the sql. 我是sql的新手。 What I am trying to do is select rows by distinct AND latest ques_id added. 我要做的是选择不同的AND行添加最新的ques_id。 Here is my table(tbl_questions) structure. 这是我的表(tbl_questions)结构。

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

This would be the desired result: 这将是期望的结果:

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

Here are the query I've tried so far: 这是我到目前为止尝试的查询:

SELECT DISTINCT ques_id, question, ans FROM tbl_questions

Just an other perspective by giving a row number by group. 通过按组给出行号,只是另一个视角。

Query 询问

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 SQL小提琴

You want the latest row for each question ? 你想要每个question的最新一行吗? You can use NOT EXISTS to return those rows: 您可以使用NOT EXISTS返回这些行:

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

Try this query 试试这个查询

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

Output 产量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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