dongsui4658 2014-03-20 22:52
浏览 30
已采纳

Codeigniter:来自一个表的多个COUNT和SUM

I have MySQL table as follow:

id | ads | status | user_id |

What would be best way to get:

  1. count of all rows where user_id=1 and status=1
  2. count of all rows where user_id=1 and status=0
  3. sum of all ads where user_id=0
  4. sum of all ads where user_id=1

My question: Can I run only one query to get all 4 results? If so, would you please explain how.

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • dro60731 2014-03-20 23:43
    关注

    Try this:

    select sum(if(status=1 and user_id=X, 1, 0)) as V1,
    sum(if(status=1 and user_id=X, ads, 0)) as V2,
    sum(if(status=0 and user_id=X, 1, 0)) as V3,
    sum(if(status=0 and user_id=X, ads, 0)) as V4
    FROM table)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (有偿)在ANSYS中 .anf文件
  • ¥45 关于#芯片#的问题:组合逻辑电路设计
  • ¥15 基与机器学习和时间序列分析预测养老服务需求趋势
  • ¥100 求连续两帧图像在水平和垂直上偏移
  • ¥15 mysql全文索引查找指定必须关键词word无效
  • ¥15 Verilog hdl密码锁设计
  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计
  • ¥15 kafka客户端跨网段访问,看日志提示连接的还剩内网地址,且访问不通
  • ¥15 关于c语言代码的问题