Вопрос

I have a table of guests:

Guests: guest_id, fname, lname, inviter_id.

Some of the guests were invited by a guest that is already in the table, so the guest he added will have the inviter guest_id in his inviter_id field.

So if i'm a guest and my guest_id is 5 and i invited John, John would have an inviter_id of 5.

Now I want to make just one SQL command, to fetch all of the guests but when I return I want the inviter_id of the guests that has them, return as the name of their inviter.

This is my SQL so far (it works):

SELECT `inviter_id`, `fname`, `lname` FROM `guests` WHERE `event_id`=12 GROUP BY `guests`.`guest_id` ORDER BY `fname`

This returns something like:

inviter_id -> 5, fname -> Ben, lname -> Paplak,inviter_id -> 26

I want it to return this:

inviter_id -> 5, fname -> Ben, lname -> Paplak,inviter_name -> 'John Doe'

Can I add that details of the inviter_id row to this one sql?

Like join this to my current sql:

SELECT `fname`, `lname` FROM `guests` WHERE inviter_id=inviter_id

(for each row that has an inviter_id that matchs a guest...)

Thanks!

Это было полезно?

Решение

Yes, you can use a left join of the guests table:

SELECT
    g.guest_id,
    g.fname,
    g.lname,
    i.fname AS inviter_fname,
    i.lname AS inviter_lname
FROM
    guests g
LEFT JOIN
    guests i
ON
    g.inviter_id = i.guest_id

You need alias names because you reference the same table twice.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top