1

我想根据一个查询中的条件将升级或标准的用户计入users['upgraded']users['standard']变量。我正在使用 mysql 和 PDO。“id”是主键

像这样的东西:

$user[upgraded] =

SELECT COUNT(*)
FROM users
AS upgraded
WHERE (status1 > 0 OR status2 > 0 OR status3 > 0)
AND upgraded = 1
AND paused = 0
AND timestamp < $timestamp
ORDER BY id DESC

$user[standard] =

SELECT COUNT(*)
FROM users
AS standard
WHERE (status1 > 0 OR status2 > 0 OR status3 > 0)
AND upgraded = 0
AND paused = 0
AND timestamp < $timestamp
ORDER BY id DESC

我如何在一个查询中得到这个?帮助将不胜感激!

4

2 回答 2

3

MySQL布尔算术,我相信这是最短的答案

SELECT  SUM(upgraded = 1) upgraded,
        SUM(upgraded = 0) downgraded
FROM    users
WHERE   (status1 > 0 OR status2 > 0 OR status3 > 0) AND 
        paused = 0  AND 
        timestamp < $timestamp

但如果您想要更友好的 RDBMS,请使用CASE

SELECT  SUM(CASE WHEN upgraded = 1 THEN 1 ELSE 0 END) upgraded,
        SUM(CASE WHEN upgraded = 0 THEN 1 ELSE 0 END) downgraded
FROM    users
WHERE   (status1 > 0 OR status2 > 0 OR status3 > 0) AND 
        paused = 0  AND 
        timestamp < $timestamp
于 2013-03-26T14:58:40.190 回答
1
select sum(if(upgraded=1,1,0)) as upgraded,
       sum(if(upgraded=0,1,0) as standard from users
  where  etc.
于 2013-03-26T15:00:30.897 回答