php - How to set "ORDER BY" for two cases?

32

In mysql, I need to set the "ORDER BY" for two cases: name or mod_1, depending on what the user selected in a combobox. My query is:

SELECT
    name,
    SUM(IF(mod = 1, 1, 0)) AS mod_1,
    SUM(IF(mod = 2, 1, 0)) AS mod_2,
    SUM(IF(mod = 3, 1, 0)) AS mod_3
FROM
    DW_RM_Log
WHERE
    ...
ORDER BY
    name (or mod_1 DESC)

Is it possible to do this in mysql or I need to code it in php? Or both?

270

Answer

Solution:

bored enough to do this for you:

$q = "SELECT
    name,
    SUM(IF(mod = 1, 1, 0)) AS mod_1,
    SUM(IF(mod = 2, 1, 0)) AS mod_2,
    SUM(IF(mod = 3, 1, 0)) AS mod_3
FROM
    DW_RM_Log
WHERE
    ...
ORDER BY ";

if ($x) {
    $q .= "name DESC";
} else {
    $q .= "mod_1 DESC";
}
 //run $q!

People are also looking for solutions to the problem: php - Simple html dom parser - nothing happens

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.