mysql返回值为min或加上sum

时间:2013-04-08 12:11:08

标签: mysql sum calculated-field

对于我的投票系统,我有两个可能的投票值。 1或-1,这个确切的值保存在数据库中。

现在我选择/计算分隔的值,如field_up和field_down。我想更改我的查询只输出一个值,如:

如果我们有'+6'和-5它应该返回+1(带+) 如果我们有-3和+2我它应该返回-1(带 - )

现在我有以下查询

SELECT 
SUM(CASE thumb when 1 then 1 else 0 end) AS "thumbs_up", 
SUM(CASE thumb when -1 then 1 else 0 end) AS "thumbs_down" 
FROM ..etc

提前致谢!

特亚。

3 个答案:

答案 0 :(得分:1)

SELECT SUM(thumb) AS votes FROM your_table

答案 1 :(得分:0)

试试这个

SELECT 
SUM( CASE WHEN thumb =1 THEN 1 ELSE 0 END) as "thumbs_up", 
SUM( CASE WHEN thumb =-1 THEN 1 ELSE 0 END) as "thumbs_down",

FROM ..etc

答案 2 :(得分:0)

一些事情。您可以大大简化您的查询:

SELECT 
SUM(thumb = 1) AS thumbs_up, 
SUM(thumb = -1) AS thumbs_down 
FROM ..etc

因为在mysql中(仅)true1false0

其次,您需要查询该查询以调整输出:

SELECT concat(if(thumbs_up > thumbs_down, '+', ''), thumbs_up - thumbs_down)
FROM (
SELECT 
    SUM(thumb = 1) AS thumbs_up, 
    SUM(thumb = -1) AS thumbs_down
    FROM ..etc
) x