Jump to content

select oldest and newest record based on id and timestamp


matthewst

Recommended Posts

I need to select records from a database based on an id number and timestamp

 

I can select based on id without a problem, whare I need help is selecting only the records with the first and latest timestamp.

 

Example:

 

table 1

id-------data--------timestamp

1--------xxx---------1111

1--------xxx---------1112

1--------xxx---------1113

2--------xxx---------1111

2--------xxx---------1112

2--------xxx---------1113

 

I only want to display records:

1--------xxx---------1111

1--------xxx---------1113

2--------xxx---------1111

2--------xxx---------1113

 

 

My current code displays all the records:

 <?php
$tableid=68;
echo "<center><strong>$tableid</strong><br><br></center>";
$query="SELECT * FROM ad_order WHERE cust_id=$tableid";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num)
{$id=mysql_result($result,$i,"id");
//////////////////////////
/////display only the first and last records of table 68
/////////////////////////
echo "<center>$id<br></center>";
$i++;}
?>

Link to comment
Share on other sites

Hmm, that seems hard.

 

I think there are two (inelegant) solutions.

 

Call MAX(timestamps) and MIN(timestamps) from your DB in two separate queries and then integrate them (I've forgotten the term for this, but you can make a "temporary table" almost).

 

Either that or lots of pre-processing, where you scroll through the data putting it into a new array when you find a min or max.

 

Not easy...

Link to comment
Share on other sites

try

SELECT r.ID, r.data, r.timestamp FROM table r
INNER JOIN 
           (SELECT ID, MIN(timestamp ) as date FROM table GROUP BY ID
            UNION 
            SELECT ID, MAX(timestamp ) as date FROM table GROUP BY ID) as a
ON r.ID = a.ID and r.timestamp = a.date
ORDER BY r.ID, r.timestamp 

Link to comment
Share on other sites

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.