php – MySQL – 如何做得更好?

前端之家收集整理的这篇文章主要介绍了php – MySQL – 如何做得更好?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

$activeQuery = MysqL_query("SELECT count(`status`) AS `active` FROM `assignments` WHERE `user` = $user_id AND `status` = 0");
$active = MysqL_fetch_assoc($activeQuery);

$FailedQuery = MysqL_query("SELECT count(`status`) AS `Failed` FROM `assignments` WHERE `user` = $user_id AND `status` = 1");
$Failed = MysqL_fetch_assoc($FailedQuery);

$completedQuery = MysqL_query("SELECT count(`status`) AS `completed` FROM `assignments` WHERE `user` = $user_id AND `status` = 2");
$completed = MysqL_fetch_assoc($completedQuery);

必须有更好的方法来做到这一点,对吧?我不知道我需要详细说明,因为你可以看到我正在尝试做什么,但有没有办法在一个查询中完成所有这些?我需要能够输出活动,失败和完成的分配,最好是在一个查询中.

最佳答案
您可以尝试这样的查询

SELECT Status,COUNT(*) StatusCount 
FROM assignments
WHERE Status IN (0,1,2)
AND User = $user_id 
GROUP BY Status

猜你在找的MySQL相关文章