简体   繁体   中英

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM