Ryan Claxton Ryan Claxton - 3 months ago 6
MySQL Question

Re-sort sql after results already generated

Is there a way to resort a mySQL sql after the results are already generated.

I have a sql that gets the results I want to display basically but the way I want to sort them depends on the result themselves. Have provided some pseudo code for clarity.

$sql = "SELECT * FROM post_info WHERE poster = 'login_user' OR replier = 'login_user'";

if ('login_user' == $row['poster']) { //sort by one column }
else { //sort by a different column }

Answer

You can sort conditionally from within the query with a CASE statement.

ORDER BY (CASE
  WHEN poster = 'login_user' THEN col1
  ELSE col2
END)`
Comments