我有2张表跟踪奖励积分。一个是摘要表,一个是详细信息表。当一个事务(奖励积分的增加或减少)发生时,一个条目被假定写入两个表不幸的是我们通过脚本错误发现有时一个条目只写入一个表。
所以现在我需要查询数据库以列出事务,而不重复重复。表中没有匹配的ID,但DateSubmitted是时间戳,2表之间的所有匹配记录共享相同的时间戳。
所以,我有2个查询
SELECT CustID, DateSubmitted, Type, Points
FROM `trans_summary`
WHERE CustID = '10009'
和
SELECT CustID, DateSubmitted, Type, PointTotal as Points
FROM `ptrans_detail`
WHERE CustID = '10009'
and DateSubmitted NOT IN
(SELECT DateSubmitted FROM `trans_summary`
WHERE CustID = '10009'
)
如何组合这两个查询以获得一个输出?
答案 0 :(得分:0)
如果你需要不同的结果,你可以使用union,如果还需要重复结果,你可以使用union all
SELECT CustID
, DateSubmitted
, Type
, Points
FROM `trans_summary`
WHERE CustID = '10009'
UNION
SELECT CustID
, DateSubmitted
, Type
, PointTotal
FROM `ptrans_detail`
WHERE CustID = '10009'
and DateSubmitted NOT IN
(SELECT DateSubmitted FROM
`trans_summary`
WHERE CustID = '10009')
或联合所有,如果还需要重复的结果
SELECT CustID
, DateSubmitted
, Type
, Points
FROM `trans_summary`
WHERE CustID = '10009'
UNION ALL
SELECT CustID
, DateSubmitted
, Type
, PointTotal
FROM `ptrans_detail`
WHERE CustID = '10009'
and DateSubmitted NOT IN
(SELECT DateSubmitted FROM
`trans_summary`
WHERE CustID = '10009')