开发者

SQL join, 3x itself?

I have a table in my database called characters. It tracks a character ID, name, marriedto, and fathersID. "marriedto" is the Character ID of a character they are wed to, and "fathersID" is the character ID of that character's father.

I'd like to do a join statement in SQL that will pull all three names. So my table mig开发者_Python百科ht look like this:

CharID CharName marriedto fatherID
1      Jeremy   2         3
2      Sarah    1         4
3      Charles  5         6

I want to run a query to return something along these lines

Jeremy, Sarah, Charles

I can get one join on itself to happen, if I want it to give me just two names, but three is escaping me.

This works for two..

"SELECT C1.name AS spouse1, C2.name AS spouse2 
        FROM characters AS C1 
            JOIN characters AS C2 
                ON C1.marriedto= C2.characters_ID";

And I have attempted this for three, but it does not work.

"SELECT C1.name AS spouse1, C2.name AS spouse2 C3.name AS father
        FROM characters AS C1 
            JOIN characters AS C2 
                ON C1.marriedto= C2.characters_ID
            LEFT JOIN characters AS C3
                ON C1.fathersID = C3.characters_ID"

How can I do this triple join of just 1 table?


Your query looks fine.. I can see only a comma missing between spouse2 and C3.name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜