Domanda

I need to retrieve data from tables by checking a single condition for multiple tables. Here is the sample example as shown below:

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');

The query:

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;

Note: The above query makes my task complete but taking too more time for execution for huge data.

Questions: 1.How to reduce time complexity?
2. Is there any better way then this?

È stato utile?

Soluzione

You can greatly reduce the cost by doing a distinct before the 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

But if you explain why you have four identical tables you can have a better answer.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top