简体   繁体   中英

mySQL query with JOIN on latest record not all records

The following code is used in a query for fetching records. It uses the electors.ID to find the corresponding voting_intention.elector from a second table.

$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"

The problem is that some electors will have more than one pledge in the voting_intentions table.

I need it to match only on the latest voting_intention.pledge based on the field votin_intention.date for each elector.

What is the simplest way of implementing that.

The rest of the code:

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

You could use a sub-select with the MAX() function. Add the following into your WHERE clause.

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

Here is a SQLFiddle of the results.

So pretty much, you only want to bother looking at the most recent row that fits the first two criteria in your code. In that case, you would want to filter out the voting_intention table beforehand to only have to worry about the most recent entries of each. There's a question/answer that shows how do do that here .

Try selecting the following instead of voting_intention (from the answer of the linked question, some table and field names replaced):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM