mySQL - 比较表行

时间:2012-07-01 02:17:24

标签: mysql database select

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

我想比较两个表,并从Database1给出结果,数据库2中不存在具有特定时间戳查询的结果。我所拥有并尝试查询的时间太长,无法搜索。

尝试:

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

我仍然无法理解这个问题。感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

有三种方法。约为performance,从最佳到最差:

  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
           )