SQLite Join 2 tables with table1 having two columns that reference table2
1
vote
2
answers
49
views
I have two tables:
jobs
CREATE TABLE IF NOT EXISTS jobs (
job_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
job_name TEXT,
prime_desc INTEGER NOT NULL REFERENCES descriptions(desc_id),
scnd_desc INTEGER NOT NULL REFERENCES descriptions(desc_id),
);
INSERT INTO jobs (job_name, prime_desc, scnd_desc) VALUES ('Soldier', 1, 5);
INSERT INTO jobs (job_name, prime_desc, scnd_desc) VALUES ('Pastor', 2, 3);
INSERT INTO jobs (job_name, prime_desc, scnd_desc) VALUES ('Firefighter', 5, 4);
descriptions
CREATE TABLE IF NOT EXISTS descriptions (
desc_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
desc_name TEXT,
);
INSERT INTO descriptions (desc_name) VALUES ('Strong');
INSERT INTO descriptions (desc_name) VALUES ('Pious');
INSERT INTO descriptions (desc_name) VALUES ('Honest');
INSERT INTO descriptions (desc_name) VALUES ('Agile');
INSERT INTO descriptions (desc_name) VALUES ('Brave');
In this example, I would like to be able to add two descriptions to a job. The code works and I can query it:
SELECT * FROM jobs;
This returns the expected result:
1|Soldier|1|5
2|Pastor|2|3
3|Firefighter|5|4
What I have been trying to do is get a query that lists the job name and the primary and secondary description names:
Firefighter|Brave|Agile
I have not been able to get that result.
I have tried:
SELECT
jobs.job_name,
desc.desc_name
FROM
jobs
JOIN
descriptions ON jobs.prime_desc = descriptions.desc_id
JOIN
descriptions ON jobs.scnd_desc = descriptions.desc_id;
This returns an error:
Parse error: ambiguous column name: descriptions.desc_name
SELECT jobs.job_name, descriptions.desc_name FROM jobs JOIN descriptions ON...
error here ---^
I searched the Internet on that error and couldn't find anything that is an example of what I'm trying to accomplish.
I tried many different combinations of:
RIGHT JOIN, LEFT JOIN, UNION, UNION ALL, ALIAS
in multiple configurations. The closest I came is with UNION, but it did not output the results as desired; here's the UNION I tried:
SELECT
jobs.job_name, descriptions.desc_name
FROM
jobs
JOIN
descriptions ON jobs.prime_desc = descriptions.desc_id
UNION
SELECT
jobs.job_name, descriptions.desc_name
FROM
jobs
JOIN
descriptions ON jobs.scnd_desc = descriptions.desc_id;
This returns:
Soldier|Strong
Pastor|Pious
Firefighter|Brave
Soldier|Brave
Pastor|Honest
Firefighter|Agile
It's returning the results as asked, so I know it's something I'm doing wrong. I just don't know what it is that I'm doing that won't print the results in one line per job, as illustrated by the Firefighter example above.
I've tried creating a column alias, a table alias, et al. I'm at a loss as to how to approach this. Any help is appreciated.
Asked by Erich4792
(13 rep)
Jul 11, 2024, 09:07 PM
Last activity: Jul 11, 2024, 10:48 PM
Last activity: Jul 11, 2024, 10:48 PM