计数字段的总和

时间:2013-11-16 00:06:27

标签: mysql

这是我的简单查询。我需要通过field1和field2对结果进行排序,但总结一下。 所以如果结果如此 FIELD1 = 5 FIELD2 = 2 和 FIELD1 = 6 FIELD2 = 4

它应该将它们(5 + 2)和(6 + 4),(7)和(10)相加,然后按顺序递减。前10然后7

    SELECT 
        COUNT(table1.ID) AS field1,  
        COUNT(table2.ID) AS field2,
    FROM table3
    LEFT JOIN table1 ON (table3.ID=table1.IDv) 
    LEFT JOIN table2 ON (table3.ID=table2.IDv)  
    GROUP BY table3.ID
    ORDER BY field1+field2 DESC

1 个答案:

答案 0 :(得分:2)

您是否介意再添加一列,例如

SELECT 
    COUNT(table1.ID) AS field1,  
    COUNT(table2.ID) AS field2,
    COUNT(table1.ID) + COUNT(table2.ID) AS field3
FROM table3
LEFT JOIN table1 ON (table3.ID=table1.IDv) 
LEFT JOIN table2 ON (table3.ID=table2.IDv)  
GROUP BY table3.ID
ORDER BY field3 DESC