Jump to content

SQL Max union (multiple columns)


karimali831

Recommended Posts

Hi

 

I'm trying to find the max value in 3 columns, new_date, reply_date and finalized_date in my table:

 

$test = safe_query("SELECT MAX(new_date) FROM (SELECT new_date AS new_date FROM ".PREFIX."cup_challenges UNION SELECT reply_date FROM ".PREFIX."cup_challenges UNION SELECT finalized_date FROM ".PREFIX."cup_challenges) AS maxval");

 

Did some research and have no idea what is wrong/if the above is correct?

The page breaks below this code.

Link to comment
https://forums.phpfreaks.com/topic/212085-sql-max-union-multiple-columns/
Share on other sites

We really need a better description than "the page breaks".

 

$test = safe_query("SELECT MAX(new_date) 
    FROM (SELECT new_date AS new_date FROM ".PREFIX."cup_challenges 
    UNION SELECT reply_date FROM ".PREFIX."cup_challenges 
    UNION SELECT finalized_date FROM ".PREFIX."cup_challenges) AS maxval");

 

You are aliasing the psuedo table for your union as "maxval", when I think you actually wanted to alias the MAX(new_date) column:

 

$test = safe_query("SELECT MAX(new_date)  AS maxval
    FROM (SELECT new_date AS new_date FROM ".PREFIX."cup_challenges 
    UNION SELECT reply_date FROM ".PREFIX."cup_challenges 
    UNION SELECT finalized_date FROM ".PREFIX."cup_challenges)");

If that is not the problem, then give us a better description of what is happening.

 

By the way, you do realize you are doing three table scans there (I think). Unless those three date columns are indexed, this query will take a long time to run. I think this is one of the few cases where you might be better off doing a little of this on the front-end.

 

SELECT MAX(new_date), MAX(reply_date), MAX(finalized_date)
    FROM ".PREFIX."cup_challenges 

 

Then find the max of the three returned values - assuming you fetch the data into an array called $row:

 $maxDate = max($row);

 

That should result in a single table scan. Although, if the three date columns ARE indexed, your UNION solution might be faster. Use EXPLAIN and look through the plan.

 

As to converting the date string. Look at the strtotime() PHP function.

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.