Filtering MySQL Query Results With PHP
For a while I’d been trying to figure out how to output a mysql query while excluding rows with duplicate values for a specific pair of column values, and then ordering by the most recent timestamp. Some if the phrases I ended up searching the web for were get all from distinct, order by then group by, exclude / remove duplicates, find duplicates, count duplicates and so on.
My ultimate solution was pretty simple and I hope it will help any one else looking for a solution to a similar problem.
$query="SELECT * FROM TABLE01 ORDER BY timestamp DESC";
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){
$valuePair=$row['col01'].$row['col02'];
$combinations[]="";
if(!(in_array($valuePair,$combinations))){
Arbitrary Code to Execute
}
$combinations[]=$valuePair;
}//end while loopIn the above code I created a variable referred to as valuePair containing the pair of values I want to check for duplicates, and an empty array called combinations which I then use to contain the valuePair’s, and check for duplicates with my if statement, if the valuePair is not found in my combination array then the code is executed, if the valuePair is contained in the combination array then the code is not executed, at the end of each while loop iteration, the new valuePair is added to the combination array.




Currents
Jose Quinones

January 27th, 2009 at 3:35 am
I sometimes spend an unhealthy amount of time figuring out a long convoluted sql statement, your solution seems to be quite elegant!
Andy Bailey’s last blog post..Chinese new year with infinity hoovers. video blog post
Wardell Reply:
January 27th, 2009 at 3:51 am
@Andy Bailey, Thank you, and thanks for stopping by.