Mysql从第二个表开始计数

时间:2012-06-12 07:19:26

标签: mysql codeigniter-2

我有一个查询,它根据$ oneid从等待表中获取所有用户。这工作得很好,但我想计算用户离开的消息数量。这些在另一个表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表

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

所以我试图像这样计算来自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,
                    (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 ) );

1 个答案:

答案 0 :(得分:1)

您的子查询应该检查user_id而不是post_idone_msg中不存在,因此它来自wait

(SELECT COUNT(id) FROM one_msg m WHERE m.user_id = a.user_id) AS count

而不是

(SELECT COUNT(id) FROM one_msg WHERE post_id = ?) AS count