Jump to content

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.

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.