Jacob Haug
Jacob Haug

Reputation: 519

MySQL Nest Join

I have a users table which contains the users information (fname, lname...etc) and a invoices table. In the invoices table I have a field called created_id which links to the user.id that created the invoice. I also have a field called staff_id which links to the staff user.id that approved the invoice.

How can I query the first and last name for both the created_id and the staff_id in a single query? Here are a few things I've tried....

SELECT  
    invoices.*,
    users.fname as created_fname,
    users.lname as created_lname
FROM
    invoices
INNER JOIN users
    ON users.id = invoices.created_id;

This works, but it only gets me the person's name that created the invoice. How can I add the staff's name to that as well....

SELECT 
    invoices.*, 
    users.fname as created_fname, 
    users.lname as created_lname,
    users2.fname as staff_fname,
    users2.lname as staff_lname
FROM invoices, users
LEFT JOIN
    invoices,
    users AS users2
ON
    users.id = invoices.created_id,
    users.id = users2.id

That doesn't work, but is closer. Any guidance or examples would be very helpful. Also, if you have any recommendations for good books on learning how to do more advanced MySQL queries that would be helpful too.

Upvotes: 3

Views: 123

Answers (1)

John Woo
John Woo

Reputation: 263703

You need to join users table twice on table Invoice.

SELECT  a.*,
        b.fname created_firstName,
        b.lname created_LastName,
        c.fname staff_firstName,
        c.lname staff_LastName      
FROM    Invoice a
        INNER JOIN users b
            ON a.created_id = b.id
        INNER JOIN users c
            ON a.staff_id = c.id

and best thing is you can concatenate their names into one using CONCAT

SELECT  a.*,
        CONCAT(b.fname, ' ', b.lname) created_fullName,
        CONCAT(c.fname, ' ', c.lname) staff_fullName        
FROM    Invoice a
        INNER JOIN users b
            ON a.created_id = b.id
        INNER JOIN users c
            ON a.staff_id = c.id

Upvotes: 4

Related Questions