php - Conditionally order by another column

713

Solution:

You should better provide some data sample and expected result, but so far you can try:

SELECT * FROM myTable1 
LEFT JOIN myTable2 b 
ON myTable1.id = b.id 
WHERE myTable1.id !='foo' 
ORDER BY CASE WHEN b.column2 IS NULL myTable1.dateColumn ELSE NULL END DESC, b.column2 ASC
322

Answer

Solution:

You can put CASE Statements inside of anORDER BY

SELECT *
FROM myTable1
LEFT JOIN myTable2 b
    ON myTable1.id = b.id
WHERE myTable1.id != 'foo'
ORDER BY CASE WHEN b.column2 IS NULL THEN 1 ELSE 0 END ASC, myTable1.dateColumn DESC
489

Answer

Solution:

You can use a function in the order part; something like the following:

SELECT * FROM myTable1 LEFT JOIN myTable2 b ON myTable1.id = b.id WHERE myTable1.id !='foo'
ORDER BY IF(b.column2 IS NULL,1,0),IF(b.column2 IS NULL,myTable1.dateColumn,NULL) DESC, b.column2 ASC

People are also looking for solutions to the problem: php - Direct stdout and stderr into the same pipe

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.