如何按 B meta_key选择user_ids并按评级meta_value 排序?
用户 ID | 元密钥 | 元值 -------------------------------------------------- --- 1 一个 1 1 乙 1 1 C 1 1 评分 9 8 一个 1 8 C 1 8 评分 99999 7 一个 1 7乙1 7 C 1 7 评分 999
我需要获取具有B meta_key 的用户的 ID,然后按用户评分值对 ID 进行排序。
试试这个:
SELECT T1.user_id
FROM yourtable T1
JOIN yourtable T2
ON T1.user_id = T2.user_id
AND T2.meta_key = 'rating'
WHERE T1.meta_key = 'B'
ORDER BY CAST(T2.meta_value AS SIGNED)
为此,您需要一个自我加入:
select t.*
from t left outer join
(select t.user_id, max(meta_value) as rating
from t
where t.meta_key = 'rating'
group by t.user_id
) r
on t.user_id = r.user_id
where meta_key = 'B'
order by r.rating