我有一个这样的记录:
$queryReplies
我想让用户在2018年7月1日至2018年7月5日之间拥有完善的有效记录。具有空值的“有效”列将被忽略。
预期结果:
mysql_stmt
之所以未选择userId#2,是因为userId#2具有2个“有效”列值,而不是等于0。
答案 0 :(得分:3)
您可以使用EXISTS
使用以下解决方案:
SELECT DISTINCT userId
FROM records r1
WHERE NOT EXISTS (
SELECT userId
FROM records r2
WHERE r1.userId = r2.userId AND IFNULL(valid, 1) = 0 AND `date` BETWEEN '2018-07-01' AND '2018-07-05'
) AND NOT valid IS NULL AND `date` BETWEEN '2018-07-01' AND '2018-07-05';
答案 1 :(得分:1)
尝试一下:
SELECT userId FROM table
WHERE (date BETWEEN '2018-07-01' AND '2018-07-05')
AND valid IS NOT NULL
GROUP BY userId
答案 2 :(得分:0)
如何测试NULL值?
无法使用比较运算符(例如=,<或<>)测试NULL值。
我们将不得不使用IS NULL和IS NOT NULL运算符。
SELECT userId FROM `user` WHERE (date BETWEEN '2018-07-01' AND '2018-07-05') AND `user.valid` != '0' AND `valid` IS NOT NULL GROUP BY `userId`;
答案 3 :(得分:0)
您可以使用not in
运算符
SELECT DISTINCT userId
FROM your_table t1
WHERE userId not in (
SELECT userId FROM your_table t2 WHERE t1.userId = t2.userId AND
valid =0 AND date >= '2018-07-01' and date<= '2018-07-05'
)
答案 4 :(得分:0)
尝试以下查询:
SELECT DISTINCT userId
FROM records r1
where 0 not in (
SELECT valid
FROM records r2
WHERE r1.userId = r2.userId
AND valid is not null
AND `date` BETWEEN '2018-07-01' AND '2018-07-05'
having count(*) > 0
);
也请here对其进行检查。
注意:如果将模式设置为Only-Group-By
,则需要更改模式才能在查询中起作用。
尽管如此,以下查询不需要更改任何设置。您可以直接运行它。
SELECT DISTINCT userId
FROM records r1
where valid is not null
group by userid
having count(*) > 0
and 0 not in ( SELECT valid
FROM records r2
WHERE r1.userId = r2.userId
AND valid is not null
and `date` BETWEEN '2018-07-01' AND '2018-07-05'
)
这是此特定查询的fiddle
希望有帮助!
答案 5 :(得分:0)
我看到SO仍然非常是一种代码编写服务。好吧,这是另一所老学校,鱼...
SELECT DISTINCT x.userid
FROM records x
LEFT
JOIN records y
ON y.userid = x.userid
AND y.valid = 0
AND y.date BETWEEN '2018-07-01' AND '2018-07-05'
WHERE x.date BETWEEN '2018-07-01' AND '2018-07-05'
AND y.userid IS NULL;