【问题标题】:Codeigniter: multiple COUNT and SUM from one tableCodeigniter:一张表中的多个 COUNT 和 SUM
【发布时间】:2014-03-20 22:52:52
【问题描述】:

我的 MySQL 表如下:

id | ads | status | user_id |

什么是最好的获得方式:

  1. 所有行的计数where user_id=1 and status=1
  2. 所有行的计数where user_id=1 and status=0
  3. 所有广告的总和where user_id=0
  4. 所有广告的总和where user_id=1

我的问题:我可以只运行一个查询来获得所有 4 个结果吗?如果是这样,请您解释一下如何。

提前谢谢你。

【问题讨论】:

  • 你想怎么做?为什么要使用 codeigniter,你想用 Active Record 来做吗?
  • 其实可以是常规的MySQL查询;无视CI。我也可以通过运行 2 个查询来获得结果:一个 for condition: status=1; status=0 时的另一个查询...但是想知道是否所有这些都可以通过运行一个查询来完成。
  • 嗯,我想的更好,也许通过下面的查询你可以做到,:P

标签: php mysql codeigniter codeigniter-2


【解决方案1】:

试试这个:

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)

【讨论】:

  • XD,我明白了,我不得不把所有的和放在一起,:P
猜你喜欢
  • 2014-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多