I am trying to sort my mysql database referencing two columns alphabetically where company_name is the primary sort but if there is no company_name then sort by last_name. I will list an example below.
company_name: (primary sort column)
1 ABC Trucking
2 Genius Heating
3
4 Xtreme Windows
last_name: (secondary column)
1 Bryant
2 Rogers
3 Flint
4 Lewis
Sorts like this:
1 ABC Trucking
3 Flint
2 Genius Heating
4 Xtreme Windows
Is this even possible or should i just merge these into an array and sort them using php?
Just make select with a column as 'name' using a case and order by it. Best shown by example.
SELECT
CASE WHEN company_name IS NULL THEN last_name ELSE company_name END AS name
FROM mytable
ORDER BY name ASC
If you really wanted to, you can also used the case statement right in the order by clause.
I think the above is really a better solution to your problem because you no longer even have the logic in the php, but you may disagree.
SELECT company_name, last_name
FROM mytable
ORDER BY CASE WHEN company_name IS NULL THEN last_name ELSE company_name END ASC
EDIT: I only assumed company_name IS NULL
is correct for you case. If you need to do this on a different condition then thats you're own exercise. Is it null? or should be comparing it to ''
instead?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With