CDbCriteria连接组有错误

时间:2014-03-30 16:40:35

标签: php yii

我有两个表dataset_type和type, 现在在类型模型中,我想创建CActiveDataProvider并使用CDbCriteria 在sql中是

 select type.name, type.description , count(dataset_type.dataset_id) as number
 from type ,dataset_type 
 where type.id=dataset_type.type_id 
 group by type.id

我如何用CDbCriteria写作

我尝试写

$criteria=new CDbCriteria;
$criteria->select='type.name, type.description, count(dataset_type.dataset_id) as number';
$criteria->join='LEFT JOIN dataset_type ON dataset_type.type_id=id';
$criteria->group='type.id';


//$criteria->compare('id',$this->id);
//$criteria->compare('LOWER(name)',strtolower($this->name) , true);
//$criteria->compare('LOWER(description)',strtolower($this->description) , true);

return new CActiveDataProvider($this, array(
    'criteria'=>$criteria,
));

但显示错误

CDbCommand failed to execute the SQL statement: SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "id" is ambiguous at character 163. The SQL statement executed was: 

SELECT COUNT(*) 
FROM (SELECT type.name, type.description, count(dataset_type.dataset_id) as number 
FROM "type" "t" 
LEFT JOIN dataset_type ON dataset_type.type_id=id 
GROUP BY type.id) sq

3 个答案:

答案 0 :(得分:0)

dataset_type.type_id=id

应该是

dataset_type.type_id=type.id

$criteria->join='LEFT JOIN dataset_type ON dataset_type.type_id=type.id';

答案 1 :(得分:0)

您应该在以下行中使用t.id: -
$ criteria-> join ='LEFT JOIN dataset_type ON dataset_type.type_id = t.id';
因为t是table table的别名。

答案 2 :(得分:0)

如果我是U,我通过createCommand在没有标准的情况下编写它 当我一起使用JOIN和GROUP BY时,我的PostgreSQL数据库出现了问题。看看这段代码:

$result = Yii::app()->db->createCommand()
        ->select("t.shop_id, s.name as name, s.schema as schema, sum(t.sales) as sales, sum(t.price) as price, sum(t.net_price) as net_price")
        ->from("pos_sales t")
        ->join("shops s", "t.shop_id=s.id")
        ->where("t.sales_year=:year AND t.sales_month=:month", array(':year' => $this->year, ':month' => $this->month))
        ->group("t.shop_id, s.name, s.schema")
        ->queryAll(); 

表格在这里

create table shops(
   id serial primary key,
   name varchar(255),
   schema varchar(255),
   store_id smallint,
   pos_sales_date date,
   active boolean
);

create table pos_sales(
   shop_id     integer NOT NULL, 
   sales_date  date NOT NULL,
   sales_year  smallint,
   sales_month smallint,
   sales       integer,
   price       numeric(12,2),
   net_price   numeric(12,2)
);
alter table pos_sales add constraint pos_sales_pkey PRIMARY KEY(shop_id, sales_date);
alter table pos_sales add constraint fk_PosSales_Shops FOREIGN KEY (shop_id) REFERENCES shops(id);