MySQL ORDER BY IF...

Hi,

I've got the following order by,  ORDER BY `date_updated` DESC, `times_downloaded` DESC

I know what I need to do, but not sure how to do it.
I need to do something like ORDER BY IF...
the field date_updated is a timestamp, I need to do order by if ($date_updated !== $date_added AND ($time - $date_updated) <= 604800), `times_downloaded` DESC

So it'll order by times_downloaded descending, but will show updated items at the top of the list regardless of times downloaded if they were updated more recently than 7 days.

I hope I've clearly enough...

Thanks guys.
LVL 6
i-CONICAAsked:
Who is Participating?
 
SharathConnect With a Mentor Data EngineerCommented:
Can you try this?
SELECT   shortname, 
         fullname, 
         category, 
         sicon, 
         date_updated, 
         date_added, 
         beta 
FROM     `soft_data` 
WHERE    category = '{$rowe[$thiscat]}' 
ORDER BY CASE 
           WHEN ($date_updated !== $date_added 
                 AND ($time - $date_updated) <= 604800) THEN 0 
           ELSE 1 
         END, 
         `times_downloaded` DESC

Open in new window

0
 
enggagrawalCommented:
0
 
nasirbestConnect With a Mentor Commented:
Add one extra column in your select cause.  like

SELECT if(($date_updated !== $date_added AND ($time - $date_updated) <= 604800), 1, 0) AS is_updated

and then use is_updated in ORDER BY clause

ORDER BY `is_updated` DESC, `date_updated` DESC, `times_downloaded` DESC

0
 
i-CONICAAuthor Commented:
Hi, Nasirbest.

Here's the full query, it's not working properly, can you see what's wrong with it? It's returning nothing.

SELECT if((`date_updated` !== `date_added` AND ($time - `date_updated`) <= 604800), 1, 0) AS is_updated, shortname, fullname, category, sicon, date_updated, date_added, beta FROM `soft_data` WHERE category = '{$rowe[$thiscat]}' ORDER BY `is_updated` DESC, `times_downloaded` DESC LIMIT 0, $limit
0
 
i-CONICAAuthor Commented:
Hi,
Thanks.
It seems to be working well. It's not showing newly updated items right at the top, but is showing them, and is showing the rest in number of times downloaded order.
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.