SQL выбирает отдельные последние значения из таблицы

У меня есть таблица с кучей строк (> 10 тыс.). Большинство строк имеют повторяющиеся значения ролей, связанные с ques_id. Я новичок в sql. То, что я пытаюсь сделать, это выбрать строки по отдельному И последнему добавленному ques_id. Вот моя структура таблицы (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

Это будет желаемый результат:

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

mysql php sql distinct
person Community    schedule 14.10.2015    source источник


Ответы (4)


arrow_upward
2
arrow_downward

Просто другая точка зрения, указывающая номер строки по группе.

Запрос

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

person Ullas    schedule 14.10.2015
comment
Это не «просто еще одна перспектива». На самом деле это может превзойти мое собственное решение! - person Strawberry; 14.10.2015

arrow_upward
0
arrow_downward

Вам нужна последняя строка для каждого question? Вы можете использовать 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)
person jarlh    schedule 14.10.2015

arrow_upward
0
arrow_downward

Попробуйте этот запрос

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
person Arun Krish    schedule 14.10.2015
comment
@Strawberry: Спасибо, что указали на это. И я отредактировал свой код. Пожалуйста, проверь это - person Arun Krish; 14.10.2015

arrow_upward

arrow_downward

person    schedule
comment
@ b0s3 b0s3 Я не предлагал вам удалить свой ответ! - person Strawberry; 14.10.2015