There are 2 tables, one for topics, the second for answers.
How to use 1 SQL query to display 5 extreme topics, with only 1 extreme answer.
In this case, new answers should raise the topic higher in the list, as it works with the use of DESC.
I tried to do this, but it doesn't work quite correctly:
SELECT `t2`.`date` AS `date`,`t1`.`name` AS `name`
FROM `quests`
AS `t1`
LEFT JOIN `answers`
AS `t2`
ON `t2`.`quest_id` = `t1`.`id`
GROUP BY `t1`.`id` DESC
How to do this correctly?
Table structures are quite simple:
quests:
+----+----------------+--------------------------------+------------+
| id | name | text | date |
+----+----------------+--------------------------------+------------+
| 1 | Quest 1 | Quest 1 Text | 1702570100 |
+----+----------------+--------------------------------+------------+
| 2 | Quest 2 | Quest 2 Text | 1702570120 |
+----+----------------+--------------------------------+------------+
answers:
+----+-----------+-----------------------------+------------+
| id | quest_id | text | date |
+----+-----------+-----------------------------+------------+
| 1 | 1 | Answer 1 | 1702570135 |
+----+-----------+-----------------------------+------------+
| 2 | 1 | Answer 2 | 1702570136 |
+----+-----------+-----------------------------+------------+
| 3 | 2 | Answer 1 | 1702570137 |
+----+-----------+-----------------------------+------------+
| 4 | 2 | Answer 2 | 1702570138 |
+----+-----------+-----------------------------+------------+
| 5 | 2 | Answer 3 | 1702570139 |
+----+-----------+-----------------------------+------------+
As a result, it should look like this:
Quest 2
- Answer 3
Quest 1
- Answer 2
I also tried doing this:
SELECT `t2`.`date` AS `date`,`t1`.`name` AS `name`
FROM `quests`
AS `t1`
JOIN (SELECT * FROM `answers` ORDER BY `date` DESC)
AS `t2`
ON `t2`.`quest_id` = `t1`.`id` GROUP BY `t1`.`id` DESC LIMIT 5
Nothing comes of it.
You will need to find the latest answer per quest_id from table answers :
Then join this dataset to tables answers and quests to get the expected output :
Results :
Demo here
Use
LEFT JOINinstead ofINNER JOINif there are questions don't have answers that also need to be listed :Which for this data :
Results :
Demo here