2012-06-28 104 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?