delato468 delato468 - 16 days ago 5
MySQL Question

Order by oldest date from more dates in a row

Each customor in my database has a own row.

For each customer i saved the product he bought and when he need a new one.

But sometimes a customer has more products like 2-3.

Example of some rows:


id | customername | product1 | dateneednew1 | product2 |dateneednew2
1. | Jacob ....... | a product| 2017-11-18 ... | a product| 2016-12-01
2. | Anna ........ | a product| 2016-12-10 ....| a product| 2017-10-10
2. | Peter ....... | a product| 2016-12-05 ... | a product| 2017-08-10


Now i wanna order by the oldest date of all "dateneednew1" - "dateneednew2"... , so in the example Jacob is first, Peter second and Anna last.

Answer
order by least(dateneednew1,dateneednew2)

And if the columns can contain NULLs

least(coalesce(dateneednew1,'3000-01-01'),coalesce(dateneednew2,'3000-01-01'))
Comments