如果在表中找到active=1,则在mysql result中完全排除用户id

hmmo2u0o  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(235)

我在php中使用mysql向客户发送一封基于特定条件的提醒电子邮件,它应该只返回结果并向客户发送电子邮件,如果该唯一客户的ca帐户为active=0,则某些客户有多个ca帐户,因此其成员资格将为me active=0和active=1
我试过下面的sql,它返回3个结果billy&daniel是正确的,它们只有active=0,所以应该显示becky的2个ca帐户都有active=0和active=1,所以sql应该查看她的查询,并意识到“no becky has active=1”,所以不应该出现。只有比利,丹尼尔回来了。

SELECT
    u.id,
    u.forename,
    u.surname,
    u.email,
    m.password,
    m.user_id,
    m.active, 
    m.promotional_code 
FROM 
    user u 
    LEFT JOIN ca_accounts c ON u.id = c.user_id 
    LEFT JOIN member m ON u.id = m.user_id 
WHERE 
    u.active = 1 AND m.active = 1 
    AND m.group_id IN (26) 
    AND (from_unixtime(m.end_date) > NOW() 
    AND from_unixtime(m.end_date) < DATE_ADD(NOW(), INTERVAL 1 DAY))  
    AND c.active = 0 
LIMIT 0, 25

产量:

id    forename surname  email   password    user_id active         
2923    Billy           billy@  NULL         2923   1   
4763    Daniel          daniel@ NULL         4763   1   
781     Beckly          becky@  NULL          781   1

它应该产生什么:

id    forename surname  email   password    user_id active         
2923    Billy           billy@  NULL         2923   1   
4763    Daniel          daniel@ NULL         4763   1

用户id 781 ca帐户表的图像

wn9m85ua

wn9m85ua1#

从您提供的信息来看,问题似乎来自表 ca_accounts ,其中多个行属于同一个用户,其值不同 active ( 0 以及 1 ).
要解决此问题,可以将 JOINca_accounts 变成一个 NOT EXISTS 中的条件 WHERE 子句的子查询,该子查询确保 ca_accounts 记录 active = 1 对于给定的用户。

SELECT
    u.id,
    u.forename,
    u.surname,
    u.email,
    m.password,
    m.user_id,
    m.active, 
    m.promotional_code 
FROM 
    user u 
    LEFT JOIN member m ON u.id = m.user_id 
WHERE 
    u.active = 1 AND m.active = 1 
    AND m.group_id IN (26) 
    AND (from_unixtime(m.end_date) > NOW() 
    AND from_unixtime(m.end_date) < DATE_ADD(NOW(), INTERVAL 1 DAY))      
    AND NOT EXISTS (
        SELECT 1
        FROM ca_accounts c 
        WHERE u.id = c.user_id AND c.active = 1
    )
LIMIT 0, 25

相关问题