Web Hosting Talk







View Full Version : MYSQL QUERY - How to sort after last added


poorapagal
04-20-2004, 08:59 PM
hi all

i am trying to figure out how to get this to show the last added album on top.. any ideas? right now it shows in alphabetical order

thx



<?
$sql = mysql_query("SELECT s.song_id, a.artist_name, a.artist_id FROM songs s, artists a WHERE s.artist_id = a.artist_id and s.artist_id <> 1 GROUP BY artist_name ORDER BY song_id desc limit 10");
while($row = mysql_fetch_array($sql)){
echo "<option value=http://www.crazefm.com/stream/browse_artist.php?artist_id=" . $row['artist_id'] . ">- " . $row['artist_name'] . "</option>";
}
?>

chipig
04-20-2004, 11:05 PM
Looking at your SQL query, i didn't see a date field.

Does your Database Table include such a Feild?

If it does its just a simple case of 'ORDER BY table.date_field'

w3needs
04-20-2004, 11:08 PM
Try this assuming that your album table is called album, and there is a column in your song table called song_album.


<?
$sql = mysql_query("SELECT a.artist_name, a.artist_id FROM songs s, artists a,album l WHERE s.artist_id = a.artist_id and s.artist_id > 1 and s.song_album = l.album_id ORDER BY l.album_id desc limit 10");
while($row = mysql_fetch_array($sql)){
echo "<option value=http://www.crazefm.com/stream/browse_artist.php?artist_id=" . $row['artist_id'] . ">- " . $row['artist_name'] . "</option>";
}
?>


This should do it. And since it looks like you are doing a good thing by prefixing your tables onto the column names(i.e., artist_id and artist_name for the artist table), you actually do not need an OO usage in your query. Instead, and if this scheme holds true on all tables, you could just use the column name as long as you reference each table used in the pulled columns and in the condition(s) for the where clause.

What I mean is that you could also use:


<?
$sql = mysql_query("SELECT artist_name, artist_id FROM songs, artists,album WHERE artist_id = artist_id and artist_id > 1 and song_album = album_id ORDER BY album_id desc limit 10");
while($row = mysql_fetch_array($sql)){
echo "<option value=http://www.crazefm.com/stream/browse_artist.php?artist_id=" . $row['artist_id'] . ">- " . $row['artist_name'] . "</option>";
}
?>


At least that usage works on my servers:)

Take care and I hope it helps...