【问题标题】:MySQL UNION vs JOIN with OR in clauseMySQL UNION vs JOIN with OR in 子句
【发布时间】:2016-04-21 04:36:26
【问题描述】:

我有一张表TableA,列[AccountID, Email]。我有另一张桌子TableB[AccountID_1, AccountID_2, email]。我需要将TableA 中的AccountIDTableB 中的AccountIDs 匹配。这些方法似乎都不起作用。第一个似乎停滞不前或只是永远(两个表都有几十万个条目)。第二个有错误"Can't reopen table: TableB".

尝试使用 OR 连接

select count(distinct TableA.id) from TableA
    JOIN TableB ON TableB.AccountID = TableA.AccountID_1 
    OR TableB.AccountID = TableA.AccountID_2
;

尝试 sql UNION

select count(distinct b.id) from (
    select * from TableA
    join TableB on TableB.AccountID = TableA.AccountID_1 
    union
    select * from TableA
    join TableB on TableB.AccountID = TableA.AccountID_2
) as b;

【问题讨论】:

  • 在联合尝试中,您第二次忘记说“在 TableB.AccountID 上加入 TableB ...”,这就是它给您错误的原因。
  • 抱歉,将我的查询放入 SO 中只是一个错误。我已经更正了。
  • 所有 3 个 AccountID* 列上是否都有索引?您是否在 join 查询上运行 explain 以查看哪些索引被使用或未被使用?
  • 这两个查询可能会返回两个不同的结果。你需要数什么? tableA 中匹配的行数?还是tableB中的行数?我们可能会猜测 `id` 在 tableA 中是唯一且非 NULL 的,但我们只是猜测。在我们编写 SQL 之前,我们需要知道我们的结果应该是什么。只要返回结果,我们就可以编写各种“有效”的查询。但如果没有规范,这些查询可能会返回任何内容,无法判断它们返回的内容是否正确。

标签: mysql join union


【解决方案1】:

你可以试试

select count(*) from TableA where
exists ( select 1 from TableB where
AccountID in (AccountID_1,AccountID_2))

【讨论】:

    【解决方案2】:

    对于第一个,选择的列名是错误的。以下似乎工作正常。

    尝试使用 OR JOIN:

    select count(distinct `TableA`.AccountID) from `TableA`
        JOIN TableB ON (TableA.AccountID = TableB.AccountID_1 
            OR TableA.AccountID = TableB.AccountID_2);
    

    尝试 SQL UNION

    select count(distinct b.AccountID) from (
        select `AccountID` from TableA
        join TableB on TableA.AccountID = TableB.AccountID_1 
        union
        select `AccountID` from TableA
        join TableB on TableA.AccountID = TableB.AccountID_2
    ) as b;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 2022-08-19
      • 1970-01-01
      • 2016-06-08
      • 2016-06-04
      • 2010-11-16
      • 1970-01-01
      相关资源
      最近更新 更多