dongzi0850 2012-08-22 13:17
浏览 71
已采纳

同一个表上的两个SUM()查询但使用不同的Where子句

I'm guessing there's a simple solution there somewhere, but it's driving me mad trying to get it to work. I want to perform two SUM() queries on the same table but they both have different WHERE clauses.

The table is used for a user voting system, so users vote on other users content. I want to be able to list the current user's activity (content/categories they've added), and combine it with details of how many other users have voted for the current users content.

Essentially i want to combine the two queries below from the same table.

SELECT category_id,
SUM(content_add) AS content_add_count,
SUM(category_add) AS category_add_count
FROM table1 WHERE user_id = '" . $user_id . "' GROUP BY category_id


SELECT SUM(normal_vote) AS agree_votes
FROM table1
WHERE issued_by_user != '" . $user_id . "'
AND user_id = '" . $user_id . "'
AND plus = '1'
GROUP BY category_id

I've tried putting the second query within another SUM() in the first query above but that obviously can't be done in MySQL, but that's what I'd like to achieve if possible.

  • 写回答

1条回答 默认 最新

  • dongqie4233 2012-08-22 13:25
    关注
    SELECT 
      category_id
      ,SUM(content_add) AS content_add_count
      ,SUM(category_add) AS category_add_count
      ,SUM(if(issued_by_user != '" . $user_id . "' AND plus = '1',normal_vote,0)) AS agree_votes
    FROM table1 
    WHERE user_id = '" . $user_id . "' 
    GROUP BY category_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)