I see the issue now. The SQL output you're showing reveals a critical problem with the subquery. The subquery is incomplete - the beginning part with SELECT MAX(created_at) FROM call_logs cl3 WHERE cl3.customer_id = cl.customer_id is missing, and it's just starting with AND cl3.customer_type_id = cl.customer_type_id.
This is a common issue when working with CodeIgniter's query builder and complex subqueries. Here's what's happening:
- You're trying to use a string-based subquery in the join condition
- The query builder is not properly parsing or is truncating the subquery
Solutions:
- Use a raw query instead - Since this is a complex query with a correlated subquery, you might be better off using a raw query:
$sql = "SELECT
cl.customer_id,
cl.customer_type_id,
COUNT(cl.id) AS total_calls,
MAX(cl.created_at) AS created_at,
cl2.details AS latest_details
FROM
call_logs AS cl
LEFT JOIN
call_logs AS cl2
ON
cl.customer_id = cl2.customer_id
AND cl.customer_type_id = cl2.customer_type_id
AND cl2.created_at = (
SELECT MAX(created_at)
FROM call_logs cl3
WHERE cl3.customer_id = cl.customer_id
AND cl3.customer_type_id = cl.customer_type_id
)
GROUP BY
cl.customer_id, cl.customer_type_id";
$query = $this->db->query($sql);
return $query->result();
- Use query builder differently - Try restructuring how you build the query:
// First fix the typo: change c2 to cl2
$join = "cl.customer_id = cl2.customer_id
AND cl.customer_type_id = cl2.customer_type_id
AND cl2.created_at = (
SELECT MAX(created_at)
FROM call_logs cl3
WHERE cl3.customer_id = cl.customer_id
AND cl3.customer_type_id = cl.customer_type_id
)";
$this->db->select([
'cl.customer_id',
'cl.customer_type_id',
'COUNT(cl.id) AS total_calls',
'MAX(cl.created_at) AS created_at',
'cl2.details AS latest_details'
])
->from("$this->tbl AS cl")
->join("$this->tbl AS cl2", $join, 'LEFT')
->group_by('cl.customer_id, cl.customer_type_id');
return $this->db->get()->result();
- Break it down with multiple queries - You could also solve this with multiple queries:
- First query to get the distinct customer_id/type combinations with counts and max dates
- Second query to join and get the details of the latest call for each combination
The direct approach with a raw query (#1) is likely the cleanest solution for this particular complex query.
Would you like me to suggest a more detailed alternative approach using multiple queries?