0

我只是不太确定这样做的正确方法。我基本上有2张桌子。两个表具有相同的结构。Database1(当前数据平均 20k 行),Database2(数据累积,在任何给定时间都可以超过 100 万行)。

我想比较这两个表,并通过特定的时间戳查询从 Database1 中给出在 Database2 中不存在的结果。我已经尝试过的查询需要很长时间才能搜索。

试过:

select distinct player from Database1
where not exists (select player from Database2 where snap = 1340981695)

SELECT Database1.player FROM Database1
INNER JOIN Database2 ON Database1.player NOT IN (Database2.player) AND Database2.snap = 1340981695
GROUP BY Database1.player

select distinct Database1.player from Database1
left join Database2 on Database1.player not in (Database2.player)
and Database2.snap = 1340981695

我仍然无法理解这一点。感谢您的帮助。

4

1 回答 1

2

有三种方法。按照性能的大致顺序,从最好到最差:

  1. 使用外连接:

    SELECT Database1.*
    FROM   Database1
      LEFT JOIN Database2
             ON Database1.id = Database2.id AND Database2.snap = 1340981695
    WHERE  Database2.id IS NULL
    
  2. 使用IN

    SELECT *
    FROM   Database1
    WHERE  id NOT IN (SELECT id FROM Database2 WHERE snap = 1340981695)
    
  3. 使用EXISTS

    SELECT *
    FROM   Database1
    WHERE  NOT EXISTS (
             SELECT *
             FROM   Database2
             WHERE id = Database1.id AND snap = 1340981695
           )
    
于 2012-07-01T09:00:02.340 回答