我在这里用谷歌搜索了 2 个小时后在这里问了这个问题,并在这里搜索了很多。但是10分钟后,我发现我得到了答案……
在查看了 select() 方法的源代码之后,
public function select($columns='*', $option='')
{
if(is_string($columns) && strpos($columns,'(')!==false)
$this->_query['select']=$columns;
else
{
if(!is_array($columns))
$columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
foreach($columns as $i=>$column)
{
if(is_object($column))
$columns[$i]=(string)$column;
else if(strpos($column,'(')===false)
{
if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
$columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
else
$columns[$i]=$this->_connection->quoteColumnName($column);
}
}
$this->_query['select']=implode(', ',$columns);
}
if($option!='')
$this->_query['select']=$option.' '.$this->_query['select'];
return $this;
}
注意第一个if语句,当传递一个字符串并且它包含“(”时,$columns变量将直接返回,这真的是我要找的!
所以解决方案是:
$sql->select('A.name as client_name, (CASE WHEN B.name = "sth" THEN B.name ELSE B.product_name END ) as product_name');
注意别名部分“as product_name”应该在 () 部分之外。