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

我想在一个查询中获得posneg分数,但我不想使用连接

所以也许是某种 IF/case 语句?

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

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' ";

有没有办法在不使用连接或子查询的情况下做到这一点?

4

9 回答 9

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。

于 2013-09-02T01:35:40.727 回答
2

关!一条CASE语句不会返回多个列,因此您需要 2 条CASE语句并将它们包装在 a 中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' ;
于 2013-09-02T01:16:36.980 回答
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

于 2013-09-02T01:44:54.307 回答
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';
于 2013-09-02T01:16:36.133 回答
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
于 2013-09-02T01:17:00.950 回答
0

不确定这是否是最佳答案(假设表中有很多行,您肯定会希望在您的 val 列上建立索引)但这当然应该有效 - 还假设您只有 1 和 -1 作为值:

SELECT count(*), val from score_history where content_id = 6 group by val;
于 2013-09-02T01:17:07.363 回答
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';
于 2013-09-02T01:18:14.763 回答
0
select count(*) 
from score_history  
where content_id = 6 && 
      (val = -1 or val=1) 
group by val

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

于 2013-09-02T01:22:52.440 回答
-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

于 2013-09-02T01:24:07.503 回答