我正在尝试查询一个用户具有多个续订但其中只有一个设置为“是”的查询。我想查询一个查询,如果所有查询都不为(0),则返回其名称。
SELECT u.id, CONCAT(u.fname, " ", u.lname) as full_name, renewals.renewRemind
FROM user u
INNER JOIN userRenewals renewals ON u.id = renewals.user_id
WHERE u.status = 1
AND renewals.renewRemind = 0
HAVING COUNT(renewals.renewRemind == 1) < 1
示例
Billy - Renewal
ID: 39 - YES
ID: 40 - NO
ID: 43 - NO
ID: 50 - NO
Vicky - Renewal
ID: 78 - NO
ID: 80 - NO
ID: 100 - NO
ID: 119 - NO
Vicky应该出现在查询中,而不是Billy。
答案 0 :(得分:0)
我会使用NOT EXISTS
:
SELECT u.id, CONCAT(u.fname, " ", u.lname) AS full_name, r.renewRemind
FROM user u INNER JOIN
userRenewals r
ON u.id = r.user_id
WHERE NOT EXISTS (SELECT 1 FROM userRenewals r1 WHERE r1.user_id = r.user_id AND r1.renewRemind = 1);
答案 1 :(得分:0)
听起来您正在寻找类似的事情:
SELECT u.id, CONCAT(u.fname, " ", u.lname) as full_name, renewals.renewRemind
FROM user u
INNER JOIN userRenewals renewals ON u.id = renewals.user_id
WHERE u.status = 1
AND renewals.renewRemind = 0
AND u.id not in (
select user_id
from renewals
where renewRemind=1
)
答案 2 :(得分:0)
这是我想出的:
SELECT u.id, CONCAT(u.fname, " ", u.lname) as full_name, renewals.renewRemind
FROM user u
JOIN userRenewals renewals ON u.id = renewals.user_id
WHERE u.status = 1
group by u.id
having sum(renewals.renewremind) = 0
这里是fiddle
编辑1:
实际上,这可能会更快,因为它不需要连接:
SELECT distinct u.id, CONCAT(u.fname, " ", u.lname) as full_name FROM user u
WHERE u.status = 1
and u.id not in (select user_id from userrenewals where renewremind=1);
答案 3 :(得分:0)
需要简单的总和检查 注意,我删除了续约条件为零的加入条件 您希望所有案例都加入,而不是预先过滤1个案例,而只将总和设为零
SELECT
u.id,
CONCAT(u.fname, " ", u.lname) as full_name,
SUM (renewals.renewRemind) rsum
FROM
user u
INNER JOIN userRenewals renewals ON u.id = renewals.user_id
WHERE
u.status = 1
HAVING rsum = 0