MySQL - 如何做得更好?

时间:2010-04-22 16:34:54

标签: php sql 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);

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

6 个答案:

答案 0 :(得分:10)

您可以尝试类似此查询的内容

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

答案 1 :(得分:2)

试试这个

$activeQuery = SELECT status, count(status) as "status count" FROM `assignments` WHERE `user` = $user_id GROUP BY `status`

编辑:按

添加分组

答案 2 :(得分:0)

您可以使用以下单个SQL语句

,而不是单独执行它们
SELECT count(*), `status` 
FROM `assignments` 
WHERE `user` = $user_id
  AND `status` in (0,1,2)
GROUP BY `status`
ORDER BY `status`

围绕结果集循环以提取结果。

答案 3 :(得分:0)

使用GROUP BY在一个查询中获取它,但在不同的行中。

$query = mysql_query("SELECT `status`, count(*) AS `num` FROM `assignments` WHERE `user` = $user_id AND `status` in (0,1,2) GROUP BY `status` ORDER BY `status` ASC");
$active_count = 0;
$failed_count = 0;
$completed_count = 0;
while ($array = mysql_fetch_assoc($query))
{
    if ($array['status'] == 0)
        $active_count = $array['num'];
    else if ($array['status'] == 1)
        $failed_count = $array['num'];
    else if ($array['status'] == 2)
        $completed_count = $array['num'];
}

答案 4 :(得分:0)

SELECT  
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 0) AS active,
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 1) AS failed,
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 2) AS completed,
FROM `assignments`
GROUP BY active, failed, completed

没有检查过标记,但这已接近或接近。

答案 5 :(得分:0)

当我有选择权时,我习惯使用预准备语句来帮助防止sql注入保护和效率(requires using mysqli)

但如果这不是一个选项,那么

SELECT
  CASE `status`
      WHEN 0 THEN `active`
      WHEN 1 THEN `failed`
      WHEN 2 THEN `completed`
      ELSE `unknown`
    END
    AS `statuslabel`,
  COUNT(status)
    AS `statuscount`
FROM `assignments` 
WHERE `user` = $escaped_user_id
GROUP BY `statuslabel`
ORDER BY `statuslabel`

请注意使用预先创建的$escaped_user_id

$escaped_user_id = mysql_real_escape_string($user_id);