我在下面有sql,想要多个ORDER BY。
SELECT
r.*,
s.uzunluq,
b.id,
au.status_id as aksessuar_status,
au.aksessuar_id,
au.aksessuar
FROM
seksiya s,
result r
LEFT JOIN bosh_seksiya_aksessuar b
ON
b.bosh_seksiya = r.model AND
b.ERK = :ses
LEFT JOIN aksessuar_up au
ON au.model_id = r.res_id AND
au.user_id = :user_id AND
au.status_id = 9
WHERE
r.user_id = :user_id AND
r.model=s.seksiya AND
s.erk = :ses AND
r.status_id IN (1,2,3,4,5)
ORDER BY
r.res_id
我认为编写php PDO对你来说并不重要,伙计们,我的问题只与这个sql有关。这个sql工作得很好,我只是想添加额外的功能。因此,请查看此列:r.status_id IN (1,2,3,4,5)
我已经Order BY r.res_id
我的问题:
我想为每个status_id
如何订购:
ORDER BY r.res_id DESC WHERE r.status_id IN (1,2)
和
ORDER BY r.res_id WHERE r.status_id IN (3,4,5)
在这个sql?
答案 0 :(得分:9)
ORDER BY IF(r.status_id IN (1,2), r.res_id, NULL) DESC, r.res_id
使用此ORDER BY
子句排序的记录集将首先显示所有带有r.status_id IN (1,2)
的记录(因为NULL
值按递减顺序排在最后),它们自己按{{1}的降序排序}};其次是按r.res_id
按升序排序的所有其他值。
答案 1 :(得分:2)
你可以使用联合语法:
SELECT * FROM ((SELECT
r.*,
s.uzunluq,
b.id,
au.status_id as aksessuar_status,
au.aksessuar_id,
au.aksessuar,
1 as query_order
FROM
seksiya s,
result r
LEFT JOIN bosh_seksiya_aksessuar b
ON
b.bosh_seksiya = r.model AND
b.ERK = :ses
LEFT JOIN aksessuar_up au
ON au.model_id = r.res_id AND
au.user_id = :user_id AND
au.status_id = 9
WHERE
r.user_id = :user_id AND
r.model=s.seksiya AND
s.erk = :ses AND
r.status_id IN (1,2)
ORDER BY
r.res_id DESC) as table1
UNION
(SELECT
r.*,
s.uzunluq,
b.id,
au.status_id as aksessuar_status,
au.aksessuar_id,
au.aksessuar,
0 as query_order
FROM
seksiya s,
result r
LEFT JOIN bosh_seksiya_aksessuar b
ON
b.bosh_seksiya = r.model AND
b.ERK = :ses
LEFT JOIN aksessuar_up au
ON au.model_id = r.res_id AND
au.user_id = :user_id AND
au.status_id = 9
WHERE
r.user_id = :user_id AND
r.model=s.seksiya AND
s.erk = :ses AND
r.status_id IN (3,4,5)
ORDER BY
r.res_id) as table2) sa table3 ORDER BY query_order