Reputation: 3226
I have a query which grabs all users from the wait table based on $oneid. This works just fine but I would like to count how many messages a user leaves. These are in another table one_msg.
function waiting_users($oneid)
{
$query_str ="SELECT a.user_id, b.email, b.username, b.fbook, c.user_id as saved_user, d.type as user_type,
FROM wait a
LEFT JOIN users b ON a.user_id=b.id
JOIN user_profiles d ON a.user_id=d.user_id
LEFT JOIN save_one c ON a.user_id=c.user_id AND c.one_id=?
WHERE a.post_id = ?
ORDER BY a.date ASC";
}
$query = $this->db->query($query_str, array( $oneid, $oneid ) );
one_msg table
+----+--------+---------+---------+---------------------+
| id | one_id | host_id | user_id | date |
+----+--------+---------+---------+---------------------+
| 3 | 127 | 268 | 270 | 2012-06-11 18:57:58 |
| 4 | 127 | 268 | 270 | 2012-06-11 21:45:11 |
| 5 | 127 | 268 | 270 | 2012-06-12 09:10:01 |
+----+--------+---------+---------+---------------------+
So I am trying to count the messages from one_msg like this but it's returning the same value for all users.
function waiting_users($oneid)
{
$query_str ="SELECT a.user_id, b.email, b.username, b.fbook, c.user_id as saved_user, d.type as user_type,
(SELECT COUNT(id) FROM one_msg WHERE post_id = ?) AS count
FROM wait a
LEFT JOIN users b ON a.user_id=b.id
JOIN user_profiles d ON a.user_id=d.user_id
LEFT JOIN save_one c ON a.user_id=c.user_id AND c.one_id=?
WHERE a.post_id = ?
ORDER BY a.date ASC";
}
$query = $this->db->query($query_str, array( $oneid, $oneid, $oneid ) );
Upvotes: 0
Views: 325
Reputation: 55524
Your sub-query should check for the user_id
instead of post_id
(which does not exist in one_msg
, so it is taken from wait
:
(SELECT COUNT(id) FROM one_msg m WHERE m.user_id = a.user_id) AS count
instead of
(SELECT COUNT(id) FROM one_msg WHERE post_id = ?) AS count
Upvotes: 1