2014-05-14 64 views
1

我需要通過檢查多個表的單個條件從表中檢索數據。這是如下圖所示的樣品例如:PostgreSQL:多個表的一個條件

create table tb1 (
    slno int, 
    name text, 
    address text 
); 

create table tb2 (
    slno int, 
    fname text, 
    faddress text 
); 

create table tb3 (
    slno int, 
    mname text, 
    maddress text 
); 

create table tb4 (
    slno int, 
    lname text, 
    laddress text 
); 

insert into tb1 values(1,'aaa','bbb'); 
insert into tb1 values(2,'2aaa','2bbb'); 
insert into tb1 values(3,'3aaa','3bbb'); 
insert into tb1 values(4,'4aaa','4bbb'); 
insert into tb1 values(5,'5aaa','5bbb'); 

insert into tb2 values(1,'faaa','fbbb'); 
insert into tb2 values(2,'f2aaa','f2bbb'); 
insert into tb2 values(3,'f3aaa','f3bbb'); 
insert into tb2 values(4,'f4aaa','f4bbb'); 
insert into tb2 values(5,'f5aaa','f5bbb'); 

insert into tb3 values(1,'maaa','mbbb'); 
insert into tb3 values(2,'m2aaa','m2bbb'); 
insert into tb3 values(3,'m3aaa','m3bbb'); 
insert into tb3 values(4,'m4aaa','m4bbb'); 
insert into tb3 values(5,'m5aaa','m5bbb'); 

insert into tb4 values(1,'laaa','lbbb'); 
insert into tb4 values(2,'l2aaa','l2bbb'); 
insert into tb4 values(3,'l3aaa','l3bbb'); 
insert into tb4 values(4,'l4aaa','l4bbb'); 
insert into tb4 values(5,'l5aaa','l5bbb'); 

查詢:

select distinct t2.slno 
from 
    tb1, 
    tb2 as t2, 
    tb3 as t3, 
    tb4 as t4 
where 
    tb1.slno = t2.slno or 
    t2.slno = t3.slno or 
    t3.slno = t4.slno; 

注:上面的查詢,使我的任務完成,但同時也有更多的時間用於執行對龐大的數據。

問題: 1.如何減少時間複雜度?
2.有沒有更好的方法呢?

+0

也許PostgreSQL分區可能有用?我最近閱讀了關於分區的以下討論,並發現它非常有啓發性。 https://github.com/fiksu/partitioned/blob/master/PARTITIONING_EXPLAINED.txt – hoipolloi

+4

爲什麼你要首先創建這些編號表?那個目標是什麼? –

+2

你在這些表上沒有任何索引。至少你應該在連接列上創建索引。並且請停止在where子句中使用舊的,過時的隱式連接,並開始使用明確的'JOIN' –

回答

1

可以大大以前join

select distinct t2.slno 
from 
    (select distinct slno from tb1) t1 
    cross join 
    (select distinct slno from tb2) t2 
    cross join 
    (select distinct slno from tb3) t3 
    cross join 
    (select distinct slno from tb4) t4 
where 
    t1.slno = t2.slno or 
    t2.slno = t3.slno or 
    t3.slno = t4.slno 

http://sqlfiddle.com/#!15/184dd/3

distinct降低成本,但如果你解釋爲什麼你有四個相同的表,你可以有一個更好的答案。

+0

非常感謝。 – Meem