带有左联接和内部联接的CodeIgniter数据库查询


CodeIgniter database query with left and inner join

我在翻译此数据库查询时遇到问题

 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";

到代码点火器的活动记录。

我试过这种方式

$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();

但错误无处不在。

您在引用时出错

$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();

您可以尝试类似的

// 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