SQL 连接,3x 本身?
我的数据库中有一个名为字符的表。它跟踪角色 ID、姓名、已婚者和父亲 ID。 “marriedto”是他们结婚的角色的角色ID,“fathersID”是该角色父亲的角色ID。
我想在 SQL 中执行一个 join 语句来提取所有三个名称。 所以我的表可能看起来像这样:
CharID CharName marriedto fatherID
1 Jeremy 2 3
2 Sarah 1 4
3 Charles 5 6
我想运行一个查询来返回一些内容,
Jeremy, Sarah, Charles
如果我希望它只给我两个名字,但三个名字却逃不过我的话,我可以让一个连接本身发生。
这对两个人有效。
"SELECT C1.name AS spouse1, C2.name AS spouse2
FROM characters AS C1
JOIN characters AS C2
ON C1.marriedto= C2.characters_ID";
我已经尝试对三个人这样做,但它不起作用。
"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"
我怎样才能只对一张表进行三重连接?
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 might 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的查询看起来不错。我可以看到
spouse2
和C3.name
之间只缺少一个逗号。Your query looks fine.. I can see only a comma missing between
spouse2
andC3.name
.