optimize the query and store result in a variable [message #606444] |
Fri, 24 January 2014 00:11 |
|
nischalinn
Messages: 118 Registered: May 2012 Location: nepal
|
Senior Member |
|
|
create table prac1 (col1 varchar2(20));
create table prac2 (col1 varchar2(20));
create table prac3 (col1 varchar2(20));
insert into parc1 values ('apple');
insert into parc1 values ('cake');
insert into parc1 values ('berries');
insert into parc1 values ('coke');
insert into parc1 values ('teset');
insert into parc2 values ('apple');
insert into parc2 values ('cake');
insert into parc2 values ('berries');
insert into parc2 values ('coke');
insert into parc3 values ('apple');
insert into parc3 values ('cake');
insert into parc3 values ('berries');
insert into parc3 values ('coke');
insert into parc3 values ('misc');
My problem is to get the data that is not common in the three tables i.e., from PRAC1 "teset" and from PRAC3 "misc".
I've written the query but is there any better way to do this?
Also I've to store the result of this query in a variable, how can I do it?
DECLARE
DIFFRESULT VARCHAR2(100);
BEGIN
SELECT DISTINCT COL1 FROM PRAC1
UNION ALL
SELECT DISTINCT COL1 FROM PRAC2
UNION ALL
SELECT DISTINCT COL1 FROM PRAC3
MINUS
(
SELECT DISTINCT COL1 FROM PRAC1
INTERSECT
SELECT DISTINCT COL1 FROM PRAC2
INTERSECT
SELECT DISTINCT COL1 FROM PRAC3
)ORDER BY 1;
// how to store the result of the above query in a variable
END;
|
|
|
|
|
|
|
Re: optimize the query and store result in a variable [message #606531 is a reply to message #606522] |
Sat, 25 January 2014 14:43 |
Solomon Yakobson
Messages: 3273 Registered: January 2010 Location: Connecticut, USA
|
Senior Member |
|
|
Kevin Meade wrote on Sat, 25 January 2014 12:09For example, we all are assuming that each table has a UNIQUE constraint on col1? Assuming this is true, this would also work.
No it would't. UNION returns distinct rows. Therefore every group will have count = 1. If you make assumption col1 is unique:
select col1
from (
SELECT COL1 FROM PRAC1
UNION ALL
SELECT COL1 FROM PRAC2
UNION ALL
SELECT COL1 FROM PRAC3
)
group by col1
having count(*) != 3
/
COL1
--------------------
misc
teset
SQL>
And this type of task when col1 isn't unique is usually resoved by using weights:
select col1
from (
SELECT COL1,1 WEIGHT FROM PRAC1
UNION ALL
SELECT COL1,2 WEIGHT FROM PRAC2
UNION ALL
SELECT COL1,3 WEIGTH FROM PRAC3
)
group by col1
having sum(distinct weight) != 6
/
COL1
--------------------
misc
teset
SQL>
SY.
|
|
|
|