具有左连接和内连接的CodeIgniter数据库查询

时间:2016-01-02 06:13:26

标签: php mysql codeigniter

我在翻译此数据库查询时遇到了麻烦

 SELECT 'conversations','conversation_id',
'conversations','conversation_subject',
MAX('conversations_messages','message_date') AS 'conversation_last_reply'
FROM 'conversations'
LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
WHERE 'conversations_members', 'user_id' = $sender_id
AND 'conversations_members','conversation_deleted' = 0
GROUP BY 'conversations'.'conversation_id'
ORDER BY 'conversation_last_reply'  DESC";

到codeignitor的活动记录。

我试过这种方式

$this->db->select('conversation_id, conversation_subject');

    $this->db->get('conversations');

     $this->db->select_max('message_date', 'conversation_last_reply');

    $this->db->get('conversations_messsages');
   $this->db->from('conversations');
   ........

但是我得到了左边和内部连接的堆叠。所以我这样尝试了

 $query = $this->db->query(
    SELECT 
          'conversations','conversation_id',
         'conversations','conversation_subject',
    MAX('conversations_messages','message_date') AS 'conversation_last_reply'
    FROM 'conversations'
    LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
    INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
    WHERE 'conversations_members', 'user_id' = $sender_id
    AND 'conversations_members','conversation_deleted' = 0
    GROUP BY 'conversations'.'conversation_id'
    ORDER BY 'conversation_last_reply'  DESC"
        );
   return $query->result();

但到处都有错误。

2 个答案:

答案 0 :(得分:1)

你的引用错误

$query = $this->db->query("SELECT 'conversations','conversation_id',
         'conversations','conversation_subject',
    MAX('conversations_messages','message_date') AS 'conversation_last_reply'
    FROM 'conversations'
    LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
    INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
    WHERE 'conversations_members', 'user_id' = $sender_id
    AND 'conversations_members','conversation_deleted' = 0
    GROUP BY 'conversations'.'conversation_id'
    ORDER BY 'conversation_last_reply' DESC"
        );
   return $query->result();

答案 1 :(得分:1)

您可以尝试这样的事情

// left, right, outer, inner, left outer, and right outer
$this->db->join('comments', 'comments.id = blogs.id', 'left');

https://www.codeigniter.com/userguide3/database/query_builder.html