mySQL 查询与最新记录的 JOIN 不是所有记录


mySQL query with JOIN on latest record not all records

以下代码用于获取记录的查询。它使用 electors.ID 从第二个表中查找相应的 voting_intention.elector。

$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表中会有不止一个承诺。

我需要它仅在基于每个选民的字段votin_intention.date的最新voting_intention.pledge上匹配。

实现这一点的最简单方法是什么。

代码的其余部分:

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'].','; }  
}

您可以将子选择与MAX()功能一起使用。 将以下内容添加到WHERE子句中。

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

下面是结果的 SQLFiddle。

所以几乎,你只想费心查看符合代码中前两个条件的最新行。在这种情况下,您可能希望事先筛选出voting_intention表,而只需要担心每个表的最新条目。这里有一个问题/答案显示了如何做到这一点。

尝试选择以下内容而不是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

问题网址:如何选择具有 MAX(列值)的行,在 SQL 中由另一列不同?