2012-06-28 42 views
0

以下代碼用於查詢記錄的提取。它使用electors.ID從第二個表中查找相應voting_intention.elector。在最新記錄上使用JOIN查詢mySQL查詢並非全部記錄

$criteria = "FROM voting_intention,electors WHERE voting_intention.elector = electors.ID AND voting_intention.pledge IN ('C','P') AND electors.postal_vote = 1 AND electors.telephone > 0" 

問題是一些選民在voting_intentions表中有多個承諾。

我需要它只匹配最新的voting_intention.pledge,根據每個選舉人的字段votin_intention.date

什麼是最簡單的實現方法。

的其餘代碼:

function get_elector_phone($criteria){ 
    $the_elector = mysql_query("SELECT * $criteria ORDER BY electors.ID ASC"); while($row = mysql_fetch_array($the_elector)) { 
    echo $row['ID'].','; } 
} 

回答

2

你可以使用一個子選擇與MAX()功能。將以下內容添加到WHERE子句中。

AND voting_intention.date = (select MAX(date) 
         from voting_intention vote2 
         where voting_intention.elector = vote2.elector) 

這裏是一個SQLFiddle of the results.

+1

一個人說話我的語言。我不知道有一個SQLFiddle這非常好 –

+0

是的,就像JSFiddle一樣。我喜歡使用它,因爲它可以讓我在將它們扔到那裏之前測試我的答案。此外,它讓提交者驗證答案,甚至嘗試其他更改。 – Seth

+0

一個輕微的免責聲明......這個答案確實取決於個人選民在voting_intention表中沒有具有完全相同日期的多個行。根據你的命名,我認爲這不太可能。 – Seth

1

那麼好看多了,你只需要費心尋找在最近的行適合這兩個標準,在你的代碼。在這種情況下,您應該事先過濾出voting_intention表,只需要擔心每個表的最新條目。有一個問題/答案顯示如何做到這一點here

嘗試選擇以下代替voting_intention(從鏈接的問題的答案,有些表和字段名稱代替):

SELECT voting_intention.* 
FROM voting_intention 
INNER JOIN 
(
SELECT elector, MAX(date) AS MaxDate 
FROM voting_intention 
GROUP BY elector 
) groupedintention ON voting_intention.elector = groupedintention.elector 
AND voting_intention.date = groupedintention .MaxDate 

問網址:How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?