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?
答案 0 :(得分:2)
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
答案 1 :(得分:1)
you jsut need to add status as group by
SELECT COUNT(*),status FROM users group by status