我有以下查询:
$result = Table1::model()->findAll(array(
'with' => array(
'table2' => array(
'joinType' => 'LEFT JOIN',
'on' => 'pk = fk AND fk=1'
)
),
'select' => array('name',
'COALESCE(table2.price, t.standardprice) AS price',
'COALESCE(table2.period, t.period) AS period')
)
);
我的目标是选择table2的字段(如果这些字段已填写),但如果这些字段为空/未找到行,则应显示原始表的字段。
但是,我的输出与预期不符。price
字段根本不显示在我的结果属性中,period
字段要么是 table2 的值,要么是空的。
编辑:也许我的SQL在某处是错误的。使用此 SQL 给了我想要的结果:
SELECT name, COALESCE(tb1.price, tb2.standardprice) as price, COALESCE(tb1.period, tb2.period) as period
FROM table1 as tb1
LEFT JOIN table2 as tb2
ON (tb1.pk= tb2.fk) AND fk=1;
然而,我看不出我当前的代码有任何区别。
编辑2:表结构:
表1(原始表)
pk (int 11) - Primary key, auto increment
name (varchar 255)
standardprice (decimal 11,2)
period (varchar 255)
fkLanguage //not relevant
photo //not relevant
description //not relevant
link //not relevant
表2
ID (int 11) - Primary key, auto increment
fk (int 11) - Foreign key, which links to pk of table1
period (varchar 255)
price (decimal 11,2)
fkType //not relevant
amount //not relevant
澄清:fk=1
确实是 JOIN 条件。如果 fk 不是 1,那么我不希望这些行连接,而是从 table1 中获取值。
您需要添加列price
来解析架构中不存在的列。
尝试修改模型表1 ()
- 添加
public $price;
- 将方法属性名称重写为以下内容:
public function attributeNames() { $colums = parent::attributeNames(); $colums[] = 'price'; return $colums; }
我认为你应该这样做:
$result = Tablename::model()->findAll(array(
'with' => array(
'tabel2' => array(
'joinType' => 'LEFT JOIN',
'on' => 'pk = fk'
)
),
'select' => array('name',
'COALESCE(tabel2.price, t.standardprice) AS price',
'COALESCE(tabel2.period, t.period) AS period'),
'condition'=> ' fk = 1 '
));
因为 fk = 1 不是 on 语句的一部分;它只是一个条件。我认为这将对你产生影响。