Skip to content

Commit 5a36a8c

Browse files
authored
Merge pull request #349 from cawpat/main
[SQL-378] - How to join only one row in joined table in SQL
2 parents cd248aa + dded59d commit 5a36a8c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
CREATE TABLE IF NOT EXISTS countries
2+
(
3+
country_id integer NOT NULL,
4+
country_name text,
5+
CONSTRAINT countries_pkey PRIMARY KEY (country_id)
6+
);
7+
8+
CREATE TABLE IF NOT EXISTS cities
9+
(
10+
city_id integer NOT NULL,
11+
country_id integer,
12+
city_name text,
13+
population bigint,
14+
CONSTRAINT cities_pkey PRIMARY KEY (city_id),
15+
CONSTRAINT country_id FOREIGN KEY (country_id)
16+
REFERENCES countries (country_id)
17+
);
18+
19+
INSERT INTO countries (country_id, country_name)
20+
VALUES
21+
(1, 'USA'),
22+
(2, 'UK'),
23+
(3, 'France'),
24+
(4, 'Thailand');
25+
26+
INSERT INTO cities (city_id, country_id, city_name, population)
27+
VALUES
28+
( 1, 1, 'Washington',689545),
29+
( 2,1,'New York', 8804190),
30+
( 3, 2, 'London', 12208100 ),
31+
( 4 , 2, 'Manchester', 2732854),
32+
( 5, 3, 'Paris', 2048472),
33+
( 6, 3, 'Nice', 353701),
34+
( 7, 4, 'Bangkok', 5588222),
35+
( 8, 4, 'Phuket', 77778);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
SELECT countries.country_id, country_name, city_id, city_name, population
2+
FROM countries
3+
JOIN cities ON countries.country_id = cities.country_id;
4+
5+
SELECT DISTINCT ON(countries.country_id)
6+
countries.country_id, country_name, city_id, city_name, population
7+
FROM countries
8+
JOIN cities ON countries.country_id = cities.country_id;
9+
10+
SELECT DISTINCT ON(countries.country_id)
11+
countries.country_id, country_name, city_id, city_name, population
12+
FROM countries
13+
JOIN cities ON countries.country_id = cities.country_id
14+
ORDER BY countries.country_id, population DESC;

0 commit comments

Comments
 (0)