以下是我的sql:
SELECT DISTINCT
U.[IP Address],
U.[Risk Rating],
COUNT( U.[IP Address] ) AS UNIXIP,
COUNT( U.[Risk Rating] ) RATINGCOUNT
FROM
Exception AS E
LEFT JOIN
tblUNIX_Archive AS U
ON E.IP_address <> U.[IP Address] -- Is using '<>' ok? instead of =
AND (U.ScanDate BETWEEN '2011-01-22' AND '2011-02-18')
group by
U.[Risk Rating],
U.[IP Address]
ORDER BY
U.[Risk Rating],
U.[IP Address]
我只需要查看tblUNIX_Archive表中不在Exception表中的唯一IP地址。我得到了多个记录。我上面的sql做错了什么?
答案 0 :(得分:2)
@Einacio,虽然你的解决方案可行,但我认为在where子句中没有输入会达到性能 - 如果记录更多,可能会非常糟糕。
@Kombucha,您可以尝试以下方法:
SELECT DISTINCT
U.[IP Address],
U.[Risk Rating],
COUNT( U.[IP Address] ) AS UNIXIP,
COUNT( U.[Risk Rating] ) RATINGCOUNT
FROM
tblUNIX_Archive AS U
LEFT JOIN
Exception AS E
ON E.IP_address = U.[IP Address] -- = to is better
AND (U.ScanDate BETWEEN '2011-01-22' AND '2011-02-18')
where E.IP_adress is null
group by
U.[Risk Rating],
U.[IP Address]
ORDER BY
U.[Risk Rating],
U.[IP Address]
更新:注意到连接的表顺序错误...纠正了。
答案 1 :(得分:1)
选择一个表中不在另一个表中的记录,你不必使用join,你必须使用NOT IN
SELECT DISTINCT
U.[IP Address],
U.[Risk Rating],
COUNT( U.[IP Address] ) AS UNIXIP,
COUNT( U.[Risk Rating] ) RATINGCOUNT
FROM
tblUNIX_Archive AS U
where U.[IP Address] NOT IN( select E.IP_address from Exception AS E)
AND (U.ScanDate BETWEEN '2011-01-22' AND '2011-02-18')
group by
U.[Risk Rating],
U.[IP Address]
ORDER BY
U.[Risk Rating],
U.[IP Address]
答案 2 :(得分:1)
左外连接将返回左表中的行,即使它们在右侧的行中不匹配。由于您需要所有Unix IP地址,因此它们应位于左侧。 (或切换到右外连接。)WHERE子句拒绝匹配的行。
SELECT DISTINCT
U.[IP Address],
U.[Risk Rating],
COUNT( U.[IP Address] ) AS UNIXIP,
COUNT( U.[Risk Rating] ) RATINGCOUNT
FROM
tblUNIX_Archive AS U left outer join
Exception AS E ON E.IP_address = U.[IP Address] AND
(U.ScanDate BETWEEN '2011-01-22' AND '2011-02-18')
WHERE
E.IP_address is NULL
group by
U.[Risk Rating],
U.[IP Address]
ORDER BY
U.[Risk Rating],
U.[IP Address]