MySQL UNION vs JOIN与条款

时间:2016-04-21 04:36:27

标签: mysql join union

我有一个表TableA,其中包含[AccountID, Email]列。我有另一张表TableB[AccountID_1, AccountID_2, email]。我需要将AccountID中的TableAAccountIDs中的TableB匹配。这些方法似乎都不起作用。第一个似乎是拖延或只是永远(两个表有几十万个条目)。第二个有错误"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;

2 个答案:

答案 0 :(得分:0)

你可以尝试

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

答案 1 :(得分:0)

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

使用OR尝试加入:

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;
相关问题