viviosoft Posted April 2, 2011 Share Posted April 2, 2011 Hello all, I have a problem I'm not sure how to tackle. I have data in a database that looks looks like this: Field1 | Field2 AA | AA Row 1 Data AA | AA Row 2 Data AA | AA Row 3 Data AB | AB Row 4 Data AB | AB Row 5 Data AB | AB Row 6 Data AC | AB Row 7 Data AC | AB Row 8 Data AC | AB Row 9 Data AC | AB Row 10 Data I would like to grab and output JUST the first AA, AB, AC and the the row data in field two? So the loop would catch the first AA then when field1 data has changed it will output the first AB and so on... So the output would look like: Row1: AA : AA Row 1 Data Row2: AB : AA Row 4 Data Row3: AC : AA Row 7 Data Is there a way to accomplish this? Any help would be great! Thanks! Quote Link to comment Share on other sites More sharing options...
Jnerocorp Posted April 2, 2011 Share Posted April 2, 2011 //make sure to connect to the database first //this code should do exactly what you want $result = mysql_query("SELECT `field1`, FIRST(`field2`) FROM `table` GROUP BY `field1`") or die(mysql_error()); $i = 0; while($row = mysql_fetch_array( $result )) { echo "Row".$i++.": ".$row['field1']." : ".$row['field2']."<br>"; } Quote Link to comment Share on other sites More sharing options...
nethnet Posted April 2, 2011 Share Posted April 2, 2011 Your SQL should look something like this: SELECT `field1`, FIRST(`field2`) FROM `table` GROUP BY `field1` This is untested, but should work. Quote Link to comment Share on other sites More sharing options...
nethnet Posted April 2, 2011 Share Posted April 2, 2011 @Jnerocorp, I don't believe he wants to print all records of the database. And using a PHP workaround to achieve what he wants is rather counterproductive, since the query will still select the entire table, which poses performance issues. The solution is in the SQL in this case. Quote Link to comment Share on other sites More sharing options...
viviosoft Posted April 2, 2011 Author Share Posted April 2, 2011 Thanks nethnet! That's what I needed. I knew there was a way to handle this. Maybe this should be moved to SQL Help? Thanks again. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.