2012-10-09 47 views
0

我有三張表,如下所示,並且試圖提取爲成員提供的最高visit_number調查問卷的次數。這個想法是爲了防止最近兩次提示訪問者的問卷被提示給訪問者(一旦訪問一段時間後visit_number字段增加了)。我對它的抨擊如下(下表),但這顯然是不正確的,我得到了成千上萬的結果。希望你至少可以看到我想要用它做帶有最大值的mysql嵌套查詢

Members 
->id 

Visits 
->id 
->visit_number 
->member_id 

Questionnaire 
->id 
->visit_id 

SELECT COUNT(*) 
FROM questionnaires q 
JOIN visits v 
ON q.visit_id = (SELECT MAX(id) FROM visits v WHERE v.member_id = ".$this->id.") 
ORDER BY q.id DESC 

回答

1

試試這個:

SELECT COUNT(*) 
FROM questionnaires q 
INNER JOIN Visits v1 ON q.visit_id = v1.id 
INNER JOIN 
(
    SELECT MAX(visit_number) MaxVisitNumber, member_id 
    FROM visits 
    GROUP BY member_id 
) v2 ON v1.member_id = v2.member_id AND v1.visit_number = v2.MaxVisitNumber 
INNER JOIN members m ON v2.member_id = m.Id 
WHERE m.Id = @someId 
+0

謝謝。假設應該是MAX(visit_number)AS MaxVisitNumber'和'v2.v'上訪問v2,我得到一個語法錯誤'near'v2 ON v1.id = v2.id' - 試圖弄清楚發生了什麼。 – bsod99

+0

@ bsod99 - 對不起,它是'member_id'而不是'id'就像'ON v1.member_id = v2.member_id'見我的編輯。 –