我正在尝试计算与另一个表中特定行相关联的行数
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
但是查询会继续返回“moz_admin”表中的总行数
这是我所做的,虽然我认为不是最有效的方法
"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];
}
重点在于,这是一个单独的SQL查询,而不是查询表中我遍历的每一行。
提前致谢。
答案 0 :(得分:0)
您应该将这些组合成一个查询。查询将是:
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;