2012-07-24 81 views
1

我剛纔問了這個問題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 

什麼我實際上是尋找是尚未答覆,然後進行排序的問題我的,他們有多少次得到答覆計數的任何問題。最好回答的問題應該在頂部。

+0

似乎有點混亂。以您的例子爲例,您期望在結果集的頂部會出現什麼問題? – 2012-07-24 05:00:05

回答

2

這會爲您提供每個問題以及與其關聯的結果數量(即使沒有結果)。他們將以最低的數量排在最前面:

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) 

這是您的想法嗎?