SQL - Self, Cross Join - Match Fixture
- Published on
- • 3 mins read•––– views
Cross Join
Cross join allows us to join each and every row of both the tables. It is similar to the cartesian product that joins all the rows.
Self Join
Self-join allows us to join a table itself. It is useful when a user wants to compare the data (rows) within the same table.
These are special joins that don't needs on
condition.
Problem
An interview question to do a inner join on table A and B with duplicate keys
suppose that in a Table named Team contains 4 records,we need to schedule a match between each team vs opposite team:
case1: Each team has to play with one another but only once.
Case2: Each team has to play with another team twice.
Could you please tell me the SQl query for both the cases?
case1: Each team has to play with one another but only once.
Answer:
-- USING POSTGRESQLdrop schema if exists temp cascade;-- cascade Automatically drop objects (tables, functions, etc.)-- that are contained in the schema.
create schema temp;
set schema 'temp';
drop table if exists team;
create table team ( country VARCHAR(15) unique not null);
insert into team values('India'),('Pakistan'),('Srilanka'),('Australia');
case1: Each team has to play with one another but only once.
-- Cross Joinselect a.country || ' vs ' || b.country fixturefrom team across join team bwhere a.country < b.countryorder by fixture asc
-- Self Joinselect a.country || ' vs ' || b.country fixturefrom team a, team bwhere a.country < b.countryorder by fixture asc
Output
fixture========Australia vs IndiaAustralia vs PakistanAustralia vs SrilankaIndia vs PakistanIndia vs SrilankaPakistan vs Srilanka
Case2: Each team has to play with another team twice.
-- Cross Joinselect a.country || ' vs ' || b.country fixturefrom team across join team bwhere a.country <> b.countryorder by fixture asc
-- Self Joinselect a.country || ' vs ' || b.country fixturefrom team a, team bwhere a.country <> b.countryorder by fixture asc
Output
fixture========Australia vs IndiaAustralia vs PakistanAustralia vs SrilankaIndia vs AustraliaIndia vs PakistanIndia vs SrilankaPakistan vs AustraliaPakistan vs IndiaPakistan vs SrilankaSrilanka vs AustraliaSrilanka vs IndiaSrilanka vs Pakistan