[英]Mysql count from a second table
I have a query which grabs all users from the wait table based on $oneid. 我有一个查询,它基于$ oneid从等待表中获取所有用户。 This works just fine but I would like to count how many messages a user leaves. 这个工作很好,但是我想计算一个用户留下多少消息。 These are in another table one_msg. 这些在另一个表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 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 |
+----+--------+---------+---------+---------------------+
So I am trying to count the messages from one_msg like this but it's returning the same value for all users. 所以我试图像这样从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 ) );
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
: 您的子查询应该检查user_id
而不是post_id
(在one_msg
中不存在,因此它是从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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.