Imnotapotato
Imnotapotato

Reputation: 5808

SQL: How to ORDER BY variables - by specific vars and not by content as it automatically does

I have this query:

SELECT * 
    FROM prods 
        JOIN keywords
            ON prods.prod_id = keywords.key_prod
        JOIN data 
            ON keywords.key_id = data.dat_id
        WHERE 
               prods.prod_id = '$id' AND data.dat_date = '$date1'
            OR prods.prod_id = '$id' AND data.dat_date = '$date2'
            OR prods.prod_id = '$id' AND data.dat_date = '$date3'
        ORDER BY kay_country ASC,
                 key_id ASC, 
                 dat_date ASC

and I want it to order $date1, $date2, $date3 by this order in the result list, although $date3 is bigger than $date1.

Is this even possible?

Upvotes: 0

Views: 31

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269873

You can use find_in_set(). However, with dates, that might be tricky. So, instead, use case:

order by key_country, key_id,
         (case when data.dat_date = '$date1' then 1
               when data.dat_date = '$date2' then 2
               when data.dat_date = '$date3' then 3
          end)

The find_in_set() version is:

order by key_country, key_id,
         find_in_set(data.dat_date, '$date1', '$date2', '$date3')

Upvotes: 1

Related Questions