Jump to content

Streamline SQL query


erme
Go to solution Solved by Barand,

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

Edited by erme
Link to comment
Share on other sites

  • Solution

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.

Edited by Barand
Link to comment
Share on other sites

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.

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.