2017-08-09 37 views
2

我有2個表,如下所示。 (每個表中有100萬條記錄)當我加入兩個表並使用OR子句執行查詢時,它非常緩慢。是否有可能加入2個表格?左外連接和OR子句很慢。過濾後可以加入嗎?

1. tblA 

id | name 
--------------------- 
1 | Bob 
2 | carol 

2. tblB 

id | name 
--------------------- 
1 | Alice 
2 | carol 

這很慢。 (或發生超時錯誤)

select * from `tblA` left outer join `tblB` on `tblA`.`name` = `tblB`.`name` where `tblA`.`name` = 'Alice' or `tblB`.`name` = 'Alice' 

每個查詢都不慢。

select * from `tblA` left outer join `tblB` on `tblA`.`name` = `tblB`.`name` where `tblA`.`name` = 'Alice' 
select * from `tblA` left outer join `tblB` on `tblA`.`name` = `tblB`.`name` where `tblB`.`name` = 'Alice' 

回答

1

我建議union all

select * 
from `tblA` a left outer join 
    `tblB` b 
     on a.name = b.name 
where a.name = 'Alice' 
union all 
select * 
from `tblA` a inner join 
    `tblB` b 
     on a.name = b.name 
where b.name = 'Alice' and a.name <> 'Alice' -- got it in the first query; 
+0

它工作。謝謝。 – zono

1

您可以使用union

select * from `tblA` where `name` = 'Alice' 
union all 
select * from `tblB` where `name` = 'Alice' 
+0

我們假定你是在'tblA'和'列tblB'是相同的。這在實際情況下似乎不合理 - 加上這將返回2列,而OP的查詢返回4. –