[英]SQL COUNT Rows from another table
am trying to count number of rows associated with a particular row from another table 我试图计算与另一个表中的特定行相关联的行数
SELECT *
FROM
(
(SELECT COUNT(*) totalusers
FROM mox_admin
, caspartition
WHERE mox_admin.partitionid = caspartition.id
)
) tita
, caspartition
ORDER
BY caspartition.id DESC
LIMIT 0,5
But the query keep returning the total count of rows in the "moz_admin" table 但查询会继续返回“moz_admin”表中的总行数
Here is what i did though i think is not the most efficient method 这是我所做的,虽然我认为不是最有效的方法
"SELECT * FROM caspartition ORDER BY caspartition.id DESC LIMIT 0, 5";
//execute the query then loop through
while($partition_data = mysqli_fetch_array($result)) {
$partition_id = $partition_data['id'];
$subquery_sql = "SELECT COUNT(*) AS totalusers FROM moz_admin WHERE partitionid = '$partition_id'";
$subquery_sql = mysqli_fetch_array(mysqli_query($conn, $subquery_sql));
$no_of_users = $subquery_sql[totalusers];
}
The whole point is making this a single SQL query instead querying the table for each row i loop through. 重点是使这个单一的SQL查询,而不是查询表中我循环的每一行。
Thanks in advance. 提前致谢。
You should combine these into one single query. 您应该将这些组合成一个查询。 The query would be:
查询将是:
SELECT cp.id, COUNT(a.partitionid) as cnt
FROM (SELECT *
FROM caspartition
ORDER BY caspartition.id DESC
LIMIT 0, 5
) cp LEFT JOIN
moz_admin a
ON a.partitionid = cp.id
GROUP BY cp.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.