leetbacoon
leetbacoon

Reputation: 1249

Join three tables together to get one value

I'm new to Postgresql and I have three tables:

=# SELECT * FROM employee_names;
 employee_id | employee_name
-------------+---------------
           1 | Johannes
           2 | Günter
           3 | Elsabeth

=# SELECT * FROM projects;
 employee_id | last_project
-------------+--------------
           1 | 5
           2 | 15
           3 | 8

=# SELECT * FROM last_project_systems_used;
 employee_id | last_project | systems_used
-------------+--------------+--------------
           1 |            5 |           11
           1 |            5 |           18
           2 |           15 |            4
           3 |            8 |           10
           3 |            8 |            7
           3 |            8 |            2

To summarize:

I need to run an insert query somewhat like the following:

    INSERT INTO last_project_systems_used 
    VALUES ((SELECT employee_id FROM employee_names 
    WHERE employee_name = 'Günter'), 
    (SELECT last_project FROM projects 
    WHERE (SELECT employee_id FROM employee_name 
    WHERE employee_name = 'Günter')), 9);

This would check what the employee_id is for Günter (2), find what his last project number was (15) and add system number 9 into the table.

That update would look like:

 employee_id | last_project | systems_used
-------------+--------------+--------------
           1 |            5 |           11
           1 |            5 |           18
           2 |           15 |            4
           3 |            8 |           10
           3 |            8 |            7
           3 |            8 |            2
           2 |           15 |            9

Though I am having trouble with the part where I get the last project number from the employee with the name Günter, since only his id is listed in the projects table and not his name.

Any help would be appreciated.

Upvotes: 0

Views: 83

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270773

Use INSERT . . . SELECT:

INSERT INTO last_project_systems_used (employee_id, last_project, systems_used)
    SELECT en.employee_id, p.last_project, 9
    FROM projects p JOIN
         employee_names en
         ON p.employee_id = en.employee_id
    WHERE en.employee_name = 'Günter';

Upvotes: 2

leetbacoon
leetbacoon

Reputation: 1249

With enough trial and error I found this this appears to do the trick, if there are better solutions to this or if my SQL sounds bad please let me know.

INSERT INTO last_project_systems_used VALUES
((SELECT employee_id FROM employee_names
WHERE employee_name = 'Günter'),
(SELECT last_project FROM projects
WHERE employee_id = (SELECT employee_id FROM employee_names
WHERE employee_name = 'Günter')), 9);

Upvotes: 0

Related Questions