Jump to content

[SOLVED] Select latest row, per person


Recommended Posts

If you have a distinct person id per row, and they are ordered so that the person's latest entry is the highest id, you can select DISTINCT(person_id) from person order by id desc;

It'll order the table by the latest entries and pull out the first row per id.

 

Mitch

 

I have tryed this and it don't work?

 

$GetAllSites = @mysql_query("SELECT DISTINCT(userID), sitePref, timeStamp, valid FROM dental_emerg WHERE valid = 0 ORDER BY timeStamp DESC");
		while ($GetAllSites2 = @mysql_fetch_array($GetAllSites))
		{
			echo $GetAllSites2['timeStamp'] . "<br>";
		}

 

If you have a distinct person id per row, and they are ordered so that the person's latest entry is the highest id, you can select DISTINCT(person_id) from person order by id desc;

It'll order the table by the latest entries and pull out the first row per id.

 

Mitch

 

What does the other query return?

 

Try it with a MAX on timestamp and grouping by the user id.

 

$GetAllSites = @mysql_query("SELECT userID, sitePref, MAX(timeStamp), valid FROM dental_emerg WHERE valid = 0 GROUP BY userID");
         while ($GetAllSites2 = @mysql_fetch_array($GetAllSites))
         {
            echo $GetAllSites2['timeStamp'] . "<br>";
         }
[\code]

try

SELECT d.userID, d.sitePref, d.timeStamp, d.valid 
FROM dental_emerg
INNER JOIN
(
    SELECT userID, MAX(timestamp) as latest 
    FROM dental_emerg
    GROUP BY userID
) as X
ON d.userID = X.userID AND d.timestamp = X.latest

That worked a treat with some minor tweaks...

SELECT dental_emerg.userID, dental_emerg.sitePref, dental_emerg.timeStamp, dental_emerg.valid 
									FROM dental_emerg
									INNER JOIN
									(
										SELECT userID, MAX(timeStamp) as latest 
										FROM dental_emerg
										GROUP BY userID
									) as X
									ON dental_emerg.userID = X.userID AND dental_emerg.timeStamp = X.latest WHERE dental_emerg.valid = 0

 

Cheers

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.