Skip to content
Advertisement

PHP: Combine these two SQL queries into one

I use MariaDB and have a table where each row has a date and a score.

I want to first show the rows where the date is 3 days old or newer, sorted by the score – then show the rest (more than 3 days old) sorted by date.

Since my date is stored in unix time, it’s fairly easy to have php calculate 3 days from before now and use that as my $scoreTimeLimit variable in the below:

Here are my two queries:

JavaScript

However, I would VERY much like to have only 1 query instead of two. Can it be done…?

Advertisement

Answer

This is a job for UNION.

JavaScript

The inner query gives you a single result set with a couple of extra columns added on to help you manage your sorting.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement