0

I'm just learning SQL and cannot do one thing.

I have 2 tables:

Persons:

CREATE TABLE Persons 
(
    `id` INT,
    `name` TEXT,
    `id_region1` INT,
    `id_region2` INT,
    PRIMARY KEY (`id`)
);

INSERT INTO Persons VALUES (1, 'pp1', 1, 1);
INSERT INTO Persons VALUES (2, 'pp2', 2, 1);
INSERT INTO Persons VALUES (3, 'pp3', 2, 3);

Region

CREATE TABLE Region 
(
    `id_region` INT,
    `region_name` TEXT,
    PRIMARY KEY (`id_region`)
);

INSERT INTO Region VALUES (1, 'AAA');
INSERT INTO Region VALUES (2, 'BBB');
INSERT INTO Region VALUES (3, 'CCC');

I would like to get this result:

1 | pp1 | AAA | AAA 
2 | pp2 | BBB | AAA 
3 | pp3 | BBB | CCC

I tried to use a join, but it cannot be done to same column.

2
  • 2
    LEFT JOIN regions twice. (One time per person region.) Commented May 4, 2020 at 15:02
  • ok but how to display that in columns? Commented May 4, 2020 at 15:11

1 Answer 1

1

LEFT JOIN region table twice. (One time per person region.)

select p.id, p.name. r1.region_name, r2.region_name
from persons p
left join region r1 on p.id_region1 = r1.id_region
left join region r2 on p.id_region2 = r2.id_region

(Do LEFT JOIN just in case, if a person has 0 or 1 region only.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.