简体   繁体   中英

PHP MySQL combine multiple fetchcolumn into a single query

I've currently got a table with users and variable user status (1, 2, 3, 4, 5 etc). I am currently calculating the number of users in each status separately

$query = "SELECT COUNT(*) FROM users WHERE status = 1";
$result = $pdo->query($query);
$users1 = $result->fetchColumn();

$query = "SELECT COUNT(*) FROM users WHERE status = 2";
$result = $pdo->query($query);
$users2 = $result->fetchColumn();

etc

I could get a fetch, then loop through all the results and add each status but I was wondering if there is a better way to do it with a query?

You can use group by and get the list with the count

SELECT status, COUNT(*)  as my_count FROM users group by status;

NB with this you can't use fetchColumn .. but fetchRow .and access by key

你jsut需要添加状态为group by

SELECT COUNT(*),status FROM users group by status

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