SQL在另一个表中按值排序

时间:2017-08-15 20:06:48

标签: mysql

我正在运行此查询以从admin表中选择display_on_website表中admin_meta值为1的行。

SELECT 
                a.sequence as sequence, 
                CONCAT(a.forename, ' ', a.surname) as name, 
                a.position as position 
            FROM 
                admin a, admin_meta am 
            WHERE 
                a.disabled = '' AND 
                a.sequence = am.user AND 
                am.field = 'display_on_website' AND 
                am.value = '1' 

我在每个admin_meta用户的website_order表格中都有一行 - 如何通过此值进行排序?

1 个答案:

答案 0 :(得分:2)

您需要两次加入admin_meta表,一次获取display_on_website值,然后再次获取website_order值,以便按顺序排序。

SELECT a.sequence, CONCAT(a.forename, ' ', a.surname) AS name, a.position
FROM admin AS a
JOIN admin_meta AS m1 on a.sequence = m1.user
JOIN admin_meta AS m2 ON a.sequence = m2.user
WHERE a.disabled = ''
AND am1.field = 'display_on_website' AND am1.value = '1'
AND am2.field = 'website_order'
ORDER BY CAST(am2.value AS DECIMAL)