我的SQL查询在NOT条件下无效

时间:2017-10-03 09:12:42

标签: php mysql sql

我的SQL查询在NOT条件下无效。 (不是u.paymentmethod = 3)请告诉我如何查询这个完美的。提前致谢

SELECT (SELECT COUNT(u.`refered`) 
         FROM user u 
         WHERE u.refered = user.user_id 
         AND  u.paymentmethod = 2 and NOT u.paymentmethod=3  ) as ref,
       user_id,
       paymentmethod 
from user  
HAVING ref < 6

3 个答案:

答案 0 :(得分:1)

您使用错误的语法not更改您的查询,如下所示:

SELECT (SELECT COUNT(u.`refered`) 
         FROM user u 
         WHERE u.refered = user.user_id 
         AND  u.paymentmethod = 2 and u.paymentmethod != 3  ) as ref,
       user_id,
       paymentmethod 
from user  
HAVING ref < 6 and user.paymentmethod = 2

修改

此外,由于u.paymentmethod != 3已经存在,您的查询不需要u.paymentmethod = 2条件

SELECT (SELECT COUNT(u.`refered`) 
             FROM user u 
             WHERE u.refered = user.user_id 
             AND  u.paymentmethod = 2) as ref,
           user_id,
           paymentmethod 
    from user  
    HAVING ref < 6 and user.paymentmethod = 2

答案 1 :(得分:0)

这是为了避免自我加入而编写它的方法......

SELECT COUNT(u.`refered`) as ref
       a.user_id,
       a.paymentmethod 
from user a
left join user u
  on u.refered = a.user_id
  and u.paymentmethod = 2 
  and u.paymentmethod <> 3 -- not needed, but might as well include it
group by user_id, paymentmethod
HAVING ref < 6

答案 2 :(得分:0)

你需要改变条件而不是条件。

SELECT (SELECT COUNT(u.`refered`) 
         FROM user u 
         WHERE u.refered = user.user_id 
         AND  u.paymentmethod = 2 AND u.paymentmethod<>3  ) as ref,
       user_id,
       paymentmethod 
from user  
HAVING ref < 6