访问查询 - 添加列以计算另一个查询中的匹配值

时间:2013-07-19 11:41:06

标签: ms-access

我想在此查询中添加另一列,用于计算来自另一个名为[qry_ip_blacklist]的查询的匹配[ip_address]值的数量

SELECT tbl_ip_addresses.ip_address, tbl_ip_addresses.selected
FROM tbl_ip_addresses
WHERE (tbl_ip_addresses.selected=True);

我为新列尝试了以下内容:

Expr1:

(SELECT COUNT(*) FROM qry_ip_blacklist WHERE ip_address = ip_address)

但这似乎显示了[qry_ip_blacklist]

中的记录总数

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,您想要使用新列显示qry_ip_blacklist表中的ip_address数量来执行第一个查询。

如果是这样且tbl_ip_addresses没有更多列,则此查询将执行此操作:

SELECT tbl_ip_addresses.ip_address, tbl_ip_addresses.selected, COUNT(qry_ip_blacklist.ip_address )
FROM tbl_ip_addresses
LEFT JOIN qry_ip_blacklist 
ON qry_ip_blacklist .ip_address = tbl_ip_addresses.ip_address
WHERE (tbl_ip_addresses.selected=True)
GROUP BY tbl_ip_addresses.ip_address, tbl_ip_addresses.selected

如果此查询仍然无效,您可以使用黑名单IP地址查询地址,而为那些没有查询的人查询另一个地址:

SELECT tbl_ip_addresses.ip_address, tbl_ip_addresses.selected, COUNT(qry_ip_blacklist.ip_address)
FROM tbl_ip_addresses
INNER JOIN qry_ip_blacklist ON qry_ip_blacklist .ip_address = tbl_ip_addresses.ip_address
WHERE (tbl_ip_addresses.selected=True)
GROUP BY tbl_ip_addresses.ip_address, tbl_ip_addresses.selected
UNION
SELECT tbl_ip_addresses.ip_address, tbl_ip_addresses.selected, 0
FROM tbl_ip_addresses
WHERE (tbl_ip_addresses.selected=True) AND tbl_ip_addresses.ip_address NOT INT (SELECT ip_addresses FROM qry_ip_blacklist)

答案 1 :(得分:0)

如果我理解正确,您需要在黑名单查询中添加GROUP BY子句:

SELECT 
 tbl_ip_addresses.ip_address
,tbl_ip_addresses.selected
,BlackList.Count

FROM tbl_ip_addresses 

LEFT JOIN (SELECT COUNT(qry_ip_blacklist.ip_address) AS Count, qry_ip_blacklist.ip_address
FROM qry_ip_blacklist
GROUP BY qry_ip_blacklist.ip_address) AS BlackList 
ON tbl_ip_addresses.ip_address = BlackList.ip_address

WHERE tbl_ip_addresses.selected = True;