MySQL按列和列值排序

时间:2013-12-24 14:46:35

标签: mysql sql select sql-order-by multiple-columns

我有一个情况,我有一个连接两个表来获取记录,其中一个表存储键值对在两个不同的列(wordpress用户元表)。

所以继承我的问题:

SELECT 
    um.user_id
FROM
    sl_job_applications as ja,
    sl_usermeta as um
WHERE
    um.user_id = ja.user_id
        AND ja.job_id = 3
        AND ja.STAGE = 'Application'
        AND ja.STATUS = 'In progress'
group by ja.user_id
order by case when (um.meta_key = 'CURRENT_TOTAL_EXPERIENCE') then -1 else 2 end,
         um.meta_value asc
LIMIT 0 , 50;

订单在这里不起作用,我的数据是

user_id             meta_key                       meta_value

3                   CURRENT_TOTAL_EXPERIENCE       6

4                   CURRENT_TOTAL_EXPERIENCE       2

5                   CURRENT_TOTAL_EXPERIENCE       1

6 

我希望你理解我的表格数据,

我的上述查询返回 6,4,5,3

但我期待这个输出: 6,5,4,3

2 个答案:

答案 0 :(得分:1)

只需将order by更改为具有max()等聚合函数和值:

order by min(case when (um.meta_key = 'CURRENT_TOTAL_EXPERIENCE') then -1 else 2 end),
         min(case when (um.meta_key = 'CURRENT_TOTAL_EXPERIENCE') then um.meta_value end) asc
LIMIT 0 , 50;

第一个检查具有该值的meta_key是否存在。第二个提取值并进行排序。

答案 1 :(得分:0)

试试这个:

SELECT um.user_id
FROM sl_job_applications AS ja
INNER JOIN sl_usermeta AS um ON um.user_id = ja.user_id
WHERE ja.job_id = 3 AND ja.STAGE = 'Application' AND ja.STATUS = 'In progress'
GROUP BY ja.user_id
ORDER BY CASE WHEN (um.meta_key = 'CURRENT_TOTAL_EXPERIENCE') THEN -1 ELSE 2 END,
         CAST(um.meta_value AS SIGNED) ASC
LIMIT 0, 50