如何在Codeigniter中加入ON CASE

时间:2017-03-27 09:41:40

标签: sql codeigniter

我想在JOIN条件下使用CASE,但它不再起作用了。

$this->db->join('user_profile ON sender.user_id = CASE WHEN mailbox.sender_user_id = 1 
                             THEN mailbox_recipient.recipient_user_id
                             ELSE mailbox.sender_user_id END');

显示像这样的错误

JOIN `user_profile ON sender`.`user_id = CASE WHEN mailbox`.`sender_user_id = 1 THEN mailbox_recipient`.`recipient_user_id ELSE mailbox`.`sender_user_id` `END`

单引号```杂乱无章

3 个答案:

答案 0 :(得分:1)

在加入声明

之前添加此项
$this->db->protect_idenifiers(FALSE);

它将删除bacticks。查询的get()语句后添加以下内容。

$this->db->protect_idenifiers(TRUE);

避免安全问题。

答案 1 :(得分:0)

我尝试使用其他替代方案,

$this->db->join('user_profile AS sender', 'sender.user_id = '.$this->table_name.'.sender_user_id');
$this->db->join('user_profile AS recipient', 'recipient.user_id = '.$this->table_name.'_recipient.recipient_user_id');

然后在我的SELECT中这样:

$this->db->select(
      $this->table_name.'.*, 
      (CASE WHEN mailbox.sender_user_id = '.$this->user_id.' THEN recipient.fullname ELSE sender.fullname END) AS user_name');

答案 2 :(得分:0)

只需在case语句中添加():

$this->db->join('user_profile ON sender.user_id = (CASE WHEN mailbox.sender_user_id = 1 THEN mailbox_recipient.recipient_user_id
ELSE mailbox.sender_user_id END)');