在1个查询中选择/总和具有不同条件的列

时间:2013-09-02 01:11:29

标签: php mysql sql

$pos = select * from score_history where content_id = 6 && val = 1 
$neg = select * from score_history where content_id = 6 && val = -1  

我希望在一个查询中获得posneg分数 但我不想使用join

所以也许是某种IF /案例陈述?

我有这个,但你可以猜到它失败了

SELECT  count(*) as total , 
CASE 
    WHEN `val` =  1  THEN count(*) as `pos` 
    WHEN `val` = -1  THEN count(*) as `neg` 
END
FROM    score_history WHERE `content_id` = '46083' ";

有没有办法在不使用连接或子查询的情况下执行此操作?

9 个答案:

答案 0 :(得分:3)

您可以利用MySQL的灵活性来处理布尔值和整数:

SELECT  count(*) total, sum(val = 1) pos, sum(val = -1) neg
FROM    score_history 
WHERE   content_id = '46083';

每当条件为真时,它为1.否则为0.不需要CASE,也不需要GROUP BY。

答案 1 :(得分:2)

关闭! CASE语句不会返回多个列,因此您需要2个CASE语句并将它们包装在SUM()中:

SELECT  count(*) as total 
  ,SUM(CASE WHEN `val` =  1  THEN 1 ELSE 0 END) as `pos`
  ,SUM(CASE WHEN `val` =  -1  THEN 1 ELSE 0 END) as `neg` 
FROM    score_history WHERE `content_id` = '46083' ;

答案 2 :(得分:0)

SELECT
SUM(CASE WHEN `val` =  1  THEN 1 ELSE O END) AS pos_count, 
SUM(CASE WHEN `val` =  -1  THEN 1 ELSE O END) AS neg_count
FROM    score_history WHERE `content_id` = '46083';

答案 3 :(得分:0)

试试这个。对不起,我无法测试,这台笔记本电脑上没有数据库。

select 
count(*) as total,
sum(case val when  1 then 1 else 0 end) as pos,
sum(case val when -1 then 1 else 0 end) as neg
from score_history
where content_id = 6

答案 4 :(得分:0)

不确定这是否是最好的答案(如果表中有很多行,你肯定希望在你的val列上有一个索引)但这当然可以工作 - 假设你只有1和-1作为值:

SELECT count(*), val from score_history where content_id = 6 group by val;

答案 5 :(得分:0)

你很亲密;试试SUM函数:

SELECT  count(*) as total 
      , sum(CASE WHEN `val` =  1 THEN 1 ELSE 0 END) as `pos` 
      , sum(CASE WHEN `val` = -1 THEN 1 ELSE 0 END) as `neg` 
FROM    score_history 
WHERE  `content_id` = '46083';

答案 6 :(得分:0)

select count(*) 
from score_history  
where content_id = 6 && 
      (val = -1 or val=1) 
group by val

我认为这个陈述应该有效,但我已经在DBMS上进行了测试。

答案 7 :(得分:0)

 SELECT  count(*) as total ,
         count(case when val = 1 then 1 else null end) as pos,
         count(case when val = -1 then 1 else null end) as neg
 FROM    score_history 
 WHERE  `content_id` = '46083';

参见 SQLFIDDLE

答案 8 :(得分:-1)

好的,很多这些答案都很接近,但无论何时使用聚合函数,都应使用group by

SELECT  count(*) as total 
      , (CASE WHEN `val` >= 0 THEN 'positive' ELSE 'negative' END) as interpreted_value
END
FROM    score_history 
WHERE  `content_id` = '46083'
GROUP BY (CASE WHEN `val` >= 0 THEN 'positive' ELSE 'negative' END);

如果您想了解如何在此处使用group by和汇总功能:https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html