Jump to content

Streamline SQL query


erme

Recommended Posts

Hi,

 

I currently have one table with a column called box, which will have values of 'one', 'two', 'three' etc. There will be 8 boxes to display on the site. The site needs to display the newest row according to column added (which will have the date added as a value). I am thinking of writing the code below to populate the 8 boxes:

while($row1 = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE box = 'one' ORDER BY added DESC LIMIT 1"))) {
    
    //echo box 1
    
}

while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE box = 'two' ORDER BY added DESC LIMIT 1"))) {
    
    //echo box 2
    
}

while($row3 = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE box = 'three' ORDER BY added DESC LIMIT 1"))) {
    
    //echo box 3
    
}

while($row4 = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE box = 'four' ORDER BY added DESC LIMIT 1"))) {
    
    //echo box 4
    
}

etc....

 

Is there a better way to streamline this?

 

Many thanks

Link to comment
https://forums.phpfreaks.com/topic/277831-streamline-sql-query/
Share on other sites

use a subquery to find latest date for each box then match against that
 

SELECT table.*
FROM table
    INNER JOIN 
        (
        SELECT box, MAX(added) as added
        FROM table
        GROUP BY box
        ) as latest USING (box, added)
ORDER BY table.box

PS Don't nest mysql statements.

there's a whole section for this in the mysql documentation - http://dev.mysql.com/doc/refman/5.5/en/example-maximum-column-group-row.html
 
does the box column actually the number name, one, two, ...? if it was the numerical number 1,2,3... it would be easier to order the output. however you cause use ORDER BY FIELD(box, 'one', 'two', ...) to order by the number name.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.