Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose I have 4 Tables say:-
1. A
2. B
3. C
4. D
SQL
create table A
(id int,
sal int);

insert into A  values(1,100);
insert into A  values(2,200);

create table B
(id int,
sal int);

insert into B  values(1,100);

create table C
(id int,
sal int);

insert into C  values(1,100);
insert into C  values(2,200);

create table D
(id int,
sal int);

insert into D  values(1,100);
insert into D  values(2,200);

and I execute following query say: -

SQL
select a.id as AID,a.sal as Asal,b.id as BID ,b.sal as Bsal , 
c.id as CID , c.sal as CSal ,d.id as Did , d.sal
from A as a,B as b , C as c ,D as d;

How does the cartesian product of 4 table works??
Posted
Updated 12-Jul-13 1:42am
v3
Comments
[no name] 12-Jul-13 6:35am    
it takes first rows of A, B , and C and product with all D, next first of A and B and second row of C, and product with all D, and so on, finally you will have 2x2x2x1 = 8 rows

1 solution

A Cartesian product is a mathematical operation which returns a set (or product set) from multiple sets. That is, for sets A and B, the Cartesian product A × B is the set of all ordered pairs (a, b) where a ∈ A and b ∈ B.
A = {1,2}; B = {3,4} 
A × B = {1,2} × {3,4} = {(1,3), (1,4), (2,3), (2,4)}


In your case set and its cartesian product will be as follows.

A = {(1,100), (2,200)}
B = {(1,100)}
C = {(1,100), (2,200)}
D = {(1,100), (2,200)}

1	100	1	100	1	100	1	100
1	100	1	100	1	100	2	200
1	100	1	100	2	200	1	100
1	100	1	100	2	200	2	200
2	200	1	100	1	100	1	100
2	200	1	100	1	100	2	200
2	200	1	100	2	200	1	100
2	200	1	100	2	200	2	200
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900