query使用连接返回错误的行,即使where子句拒绝它

inb24sb2  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(255)

我试图计算行数,但问题是它返回where子句中描述的不包括的行数。
此查询应返回在中至少有一行的网络数 network_logs table和table network_log 行的类型必须为“entrance”,状态代码为0,但由于某些原因,它返回的行的类型也不同。

SELECT DISTINCT n.id as test_count 
FROM networks as n
INNER JOIN network_sessions AS ns ON ns.network_id = n.id
LEFT JOIN network_logs AS nl ON nl.network_session_id = ns.id AND nl.type = "ENTRANCE" AND nl.status_code = 0
WHERE n.status_time BETWEEN '2020-07-01 00:00:00' AND '2020-07-31 00:00:59' AND nl.created_at
BETWEEN '2020-07-01 00:00:00' AND '2020-07-31 00:00:59'
GROUP BY n.id
HAVING COUNT(nl.id) >= 1;

我做错了什么?

kkbh8khc

kkbh8khc1#

我会检查where子句,以便在和上使用正确的优先级

SELECT DISTINCT n.id as test_count 
FROM networks as n
INNER JOIN network_sessions AS ns ON ns.network_id = n.id
LEFT JOIN network_logs AS nl ON nl.network_session_id = ns.id AND nl.type = "ENTRANCE" AND nl.status_code = 0
WHERE 
    n.status_time BETWEEN ('2020-07-01 00:00:00' AND '2020-07-31 00:00:59') 
AND 
    nl.created_at BETWEEN ('2020-07-01 00:00:00' AND '2020-07-31 00:00:59')
GROUP BY n.id
HAVING COUNT(nl.id) >= 1;

如果没有样本数据和预期结果,这是未经测试的。可能是你要复习外文,成为一个或imho,但没有样本数据是不可能理解的

z9ju0rcb

z9ju0rcb2#

像下面这样试试

SELECT DISTINCT n.id as test_count 
FROM networks as n
INNER JOIN network_sessions AS ns ON ns.network_id = n.id
JOIN network_logs AS nl ON nl.network_session_id = ns.id 

WHERE n.status_time BETWEEN '2020-07-01 00:00:00' AND '2020-07-31 00:00:59' 
AND nl.created_at BETWEEN '2020-07-01 00:00:00' AND '2020-07-31 00:00:59'
AND nl.type = "ENTRANCE" AND nl.status_code = 0

因为网络日志至少包含1个值,所以您可以应用内部连接,而不需要count()

qni6mghb

qni6mghb3#

此查询应返回在网络日志表中至少有一行且网络日志行的类型必须为“入口”且状态代码为0的网络数
这些条件在 ON a的子句 LEFT JOIN . 如果你真的想按它们过滤,那么使用 INNER JOIN --和/或将条件移至 WHERE 条款。
我还怀疑你想要7月份的所有行,而不仅仅是最后一天的第一分钟。所以:

SELECT DISTINCT n.id as test_count 
FROM networks n JOIN
     network_sessions ns
     ON ns.network_id = n.id JOIN
     network_logs nl
     ON nl.network_session_id = ns.id
WHERE nl.type = 'ENTRANCE' AND nl.status_code = 0 AND
      n.status_time >= '2020-07-01' AND 
      n.status_time < '2020-08-01' AND 
      nl.created_at >= '2020-07-01' AND
      nl.created_at < '2020-08-01' ;

相关问题