我刚问了这个问题Find the oldest record in a join between two tables我的问题得到了很好的回答。问题是这不是我想要的(我的错)
考虑以下 MySQL 表
Table: Questions
ID
Table: Results
ID
Created - When this record was added.
Q_ID - A FK to the Question table
示例数据
Table: Questions
ID
----
1
8
15
55
Table: Results
ID | Created | Q_ID
--------------------
1 | 12:02 | 1
2 | 12:03 | 15
3 | 12:04 | 8
使用以下查询,它将返回所有没有关联结果的记录,如果所有记录都有结果,那么它将返回结果最早的问题。
SELECT *
FROM
questions
LEFT JOIN results
ON results.q_id = questions.id
ORDER BY
ISNULL(results.id) DESC, results.created ASC
LIMIT 1
我实际上要寻找的是任何尚未回答的问题,然后根据回答的次数对问题进行排序。最少回答的问题应该在顶部。
最佳答案
这将为您提供每个问题,以及与之关联的结果数量(即使不存在任何结果)。它们将以最少的数量排列在顶部:
SELECT Questions.ID, COUNT(Results.ID) Result_Count
FROM
Questions
LEFT JOIN Results ON Questions.ID = Results.Q_ID
GROUP BY Questions.ID
ORDER BY COUNT(Results.ID)
这是你的想法吗?
关于mysql - 查找具有最少关联记录的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11624104/