Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query with 2 foreign keys from one table

Tags:

sql

I have a table with two foreign keys in one table.

Table PROJECTS
        - Id
        - Owner - FK
        - Client - FK 

and

table USERS
        - Id
        - Name

I'd like to select all projects with appropriate names of the owner and client

The result should look like:

Id | OwnerName | ClientName

like image 602
user137348 Avatar asked Aug 17 '26 04:08

user137348


1 Answers

You just need two joins to that table.

SELECT  p.Id,
        u1.Name OwnerName,
        u2.Name ClientName
FROM    Projects p
        LEFT JOIN
                Users u1
                ON p.Owner = u1.Id
        LEFT JOIN
                Users u2
                ON p.Client = u2.Id
like image 70
David M Avatar answered Aug 18 '26 18:08

David M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!