【问题标题】:SQL SERVER Msg 8120, Level 16, State 1SQL SERVER 消息 8120,级别 16,状态 1
【发布时间】:2016-09-01 18:32:49
【问题描述】:

只是不明白为什么我必须聚合每个表列,只是为了让 SQL SERVER 以另一种方式查看。很难理解。我为什么要这样做:

$this->db->select("MAX(c.id),MAX(c.name),MAX(c.phone)");
$this->db->select('MAX(state.name) as st_nm');
$this->db->select('MAX(lga.name) as "lga_nm"');
$this->db->select('MAX(cp2.point_name),MAX(cp2.location)');
$this->db->select('SUM(pr.amount) as "amt"');
$this->db->from('consultant as c');
$this->db->join('state','state.id=c.state','inner');
$this->db->join('lga','lga.id=c.lga','inner');
$this->db->join('collection_point2 as cp2','cp2.point_code=c.collection_point','inner');
$this->db->join('payment_records as pr','pr.consultant_id=c.unique_id','inner');
$this->db->where('c.agent_id',$agent);
$this->db->group_by('c.id');
$this->db->order_by('c.id');   

只是为了避免这种情况:

Msg 8120, Level 16, State 1, Line 1 Column ... is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

【问题讨论】:

标签: php sql-server codeigniter


【解决方案1】:

我知道,您总是会遇到这种情况,即您的脑海中会出现同样的问题。为什么所有列都需要它?

您的选择:

  1. 分离出聚合逻辑,不要将所有列都放在一个查询中。比如说,让一个查询返回您“来自顾问和付款记录的 c.id, SUM(pr.amount)”。

  2. 使用上面的表来连接其他表(state,lga,consultant),并且这个查询的任何列都不需要聚合。

我建议比较这些查询的执行时间并根据性能做出决定。

推理:这就是“group by”子句的设计方式。尽管实际场景会拖累开发人员构建这种看起来很荒谬的查询,其中对每一列应用聚合只是为了让它吐出所需的数据。

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    相关资源
    最近更新 更多