我有两个表:table1
和table2
。在两个表msg_id
中都很常见。
我写了以下查询:
select alert.MSG_ID, alert.ACTION,
alert.ALERT_ID, alert.CONTACT_DETAIL,
alert.TRXREFNUMBER, alert.TARGET_SYSTEM,
log.MSG_ID, log.ACTION, log.ERR_CODE, log.CONTACT_DETAIL
from bnea.table1 alert,
bnea.table2 log
where not exists (select a.MSG_ID
from bnea.table2
where alert.MSG_ID = log.MSG_ID);
然而它不起作用。当我执行上面的查询时,它会交叉连接所有记录。
任何人对此类或类似的查询有经验吗?
答案 0 :(得分:0)
您可以使用此格式的查询来获取输出而不会出现任何重复结果。
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
答案 1 :(得分:0)
您已经包含了一个CROSS JOIN(偶然),原始查询(重新格式化):
SELECT
alert.MSG_ID
, alert.ACTION
, alert.ALERT_ID
, alert.CONTACT_DETAIL
, alert.TRXREFNUMBER
, alert.TARGET_SYSTEM
, log.MSG_ID
, log.ACTION
, log.ERR_CODE
, log.CONTACT_DETAIL
FROM bnea.table1 alert
, bnea.table2 log --<<<<< this is a cross join !!!
WHERE NOT EXISTS (
SELECT
a.MSG_ID
FROM bnea.table2
WHERE alert.MSG_ID = log.MSG_ID
);
应该是:
SELECT
alert.MSG_ID
, alert.ACTION
, alert.ALERT_ID
, alert.CONTACT_DETAIL
, alert.TRXREFNUMBER
, alert.TARGET_SYSTEM
FROM bnea.table1 alert
WHERE NOT EXISTS (
SELECT NULL
FROM bnea.table2 log
WHERE alert.MSG_ID = log.MSG_ID
);
注意:
答案 2 :(得分:0)
如何使用FULL OUTER JOIN?
SELECT
alert.MSG_ID
, alert.ACTION
, alert.ALERT_ID
, alert.CONTACT_DETAIL
, alert.TRXREFNUMBER
, alert.TARGET_SYSTEM
, log.MSG_ID
, log.ACTION
, log.ERR_CODE
, log.CONTACT_DETAIL
FROM bnea.table1 alert FULL OUTER JOIN bnea.table2 log ON(alert.MSG_ID = log.MSG_ID)
WHERE log.MSG_ID <> alert.MSG_ID