Mysql IF语句返回问题

时间:2015-02-21 14:47:11

标签: mysql

我有这个查询,其中IF行只部分返回正确的结果:

选择

COALESCE((SELECT COUNT(ID) FROM USERS_BUCKETS WHERE USERS_BUCKETS.USERID = USERS.ID),0) AS ADDED,
COALESCE((SELECT SUM(CASE WHEN USERS_BUCKETS.STATUS='Completed' THEN 1 ELSE 0 END) FROM USERS_BUCKETS WHERE USERS_BUCKETS.USERID = USERS.ID),0) AS DONE,
COALESCE((SELECT COUNT(ID) FROM USERS_LIKES WHERE USERS_LIKES.USERID = USERS.ID),0) AS NUM_LIKES,
COALESCE((SELECT COUNT(ID) FROM FOLLOW WHERE FOLLOW.USER_ID=USERS.ID),0) AS FOLLOWING,
COALESCE((SELECT COUNT(ID) FROM FOLLOW WHERE FOLLOW.FOLLOW_ID=USERS.ID),0) AS FOLLOWERS,

(SELECT IF(ADDED >= 5,1,0)) AS IFADDED,
(SELECT IF(DONE >= 3,1,0)) AS IFDONE,
(SELECT IF(NUM_LIKES >= 5,1,0)) AS IFNUM_LIKES,
(SELECT IF(FOLLOWING >= 5,1,0)) AS IFFOLLOWING,
(SELECT IF(FOLLOWERS >= 3,1,0)) AS IFFOLLOWERS,

(SELECT IF(ADDED >= 5,1,0) + IF(DONE >= 3,1,0) + IF(NUM_LIKES >= 5,1,0) + IF(FOLLOWING >= 5,1,0) + IF(FOLLOWERS >= 3,1,0)) AS PROGRESS

FROM USERS 
WHERE USERS.ID=?

结果:

ADDED: 20
IFADDED: 1

DONE: 9
IFDONE: 0  //should be 1

NUM_LIKES: 11
IFNUM_LIKES: 1

FOLLOWING: 11
IFFOLLOWING: 0 //should be 1

FOLLOWERS: 10
IFFOLLOWERS: 0 //should be 1

PROGRESS: 2

怎么了?所有IF值应为1,PROGRESS应为5。 注意:我在php中使用PDO,但我认为这根本不重要。

1 个答案:

答案 0 :(得分:0)

我不知道为什么你的代码有效。这些列绝对不是查询中先前定义的列别名。

要做你想做的事,请使用子查询并简化逻辑:

SELECT u.*, (ADDED >= 5) AS IFADDED,
       (DONE >= 3) AS IFDONE,
       (NUM_LIKES >= 5) AS IFNUM_LIKES,
       (FOLLOWING >= 5) AS IFFOLLOWING,
       (FOLLOWERS >= 3) AS IFFOLLOWERS,
       ((ADDED >= 5) + (DONE >= 3) + (NUM_LIKES >= 5) + (FOLLOWING >= 5) + 
        (FOLLOWERS >= 3)
       ) AS PROGRESS  
FROM (SELECT COALESCE((SELECT COUNT(ID) FROM USERS_BUCKETS WHERE USERS_BUCKETS.USERID = USERS.ID),0) AS ADDED,
             COALESCE((SELECT SUM(CASE WHEN USERS_BUCKETS.STATUS='Completed' THEN 1 ELSE 0 END) FROM USERS_BUCKETS WHERE USERS_BUCKETS.USERID = USERS.ID),0) AS DONE,
             COALESCE((SELECT COUNT(ID) FROM USERS_LIKES WHERE USERS_LIKES.USERID = USERS.ID),0) AS NUM_LIKES,
             COALESCE((SELECT COUNT(ID) FROM FOLLOW WHERE FOLLOW.USER_ID=USERS.ID),0) AS FOLLOWING,
             COALESCE((SELECT COUNT(ID) FROM FOLLOW WHERE FOLLOW.FOLLOW_ID=USERS.ID),0) AS FOLLOWERS
      FROM USERS 
      WHERE USERS.ID = ?
     ) u;

这利用了MySQL在数字上下文中将布尔值视为整数的事实,其中" 1"为真和" 0"为假。

编辑:我还应注意coalesce()是不必要的,因为count()会在没有匹配时返回0