У меня есть таблица с кучей строк (> 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
Ответ 1 · рейтинг 2 · Ullas
Просто другая точка зрения, указывающая номер строки по группе.
Запрос
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
Ответ 2 · jarlh
Вам нужна последняя строка для каждого 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)
Ответ 3 · Arun Krish
Попробуйте этот запрос
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