SQL 内连接和外键
SQL inner join and foreign keys
我有两个table。
table 个“人”包括“id”、“fname”、“lname”。
table“关系”包括“parent”、“child”(引用 persons.id 作为外键)
我想打印每个 parent 名字+姓氏和他们的 children 姓氏。
所以基本上我想打印这个:
George|Cameron|Eddy|Cameron //Father-son
George|Cameron|Stephen|Cameron //Father-son
George|Cameron|Lynda|Cameron //Father-daughter
Elisabeth|Cameron|Eddy|Cameron //Mother-son
Elisabeth|Cameron|Stephen|Cameron //Mother-son
Elisabeth|Cameron|Lynda|Cameron //Mother-daughter
etc...
我做了这样的东西:
SELECT
persons.fname, //parents fname => yes, it works
persons.lname, //parents lname => yes, it works
?, //children fname => I have no clue
? //children lname => I have no clue
FROM
persons
INNER JOIN
relationships
ON
persons.id = relationships.parent
我知道我快到了,但我就是不知道该输入什么而不是“?”。
因为,基本上,我需要来自完全相同字段的两次信息,一次是 parents,一次是 children。
但是我如何才能表明我需要前两个参数的 parents 名称和后两个参数的 children 名称(因为它们都是“persons.fname”和“persons.lname")?
PS: 如果能问个最简单直接的方法,让我能学好基础知识,不胜感激
谢谢。
可能最简单的方法是使用 table 别名。
SELECT
parent.fname, //parents fname
parent.lname, //parents lname
children.fname, //children fname
children.lname //children lname
FROM
persons parent
INNER JOIN
relationships
ON
persons.id = relationships.parent
INNER JOIN
persons children
ON relationships.child = children.id
这允许您引用相同的 table 两次,但使用不同的别名,这样您就可以保持它们的正确性。
我有两个table。
table 个“人”包括“id”、“fname”、“lname”。
table“关系”包括“parent”、“child”(引用 persons.id 作为外键)
我想打印每个 parent 名字+姓氏和他们的 children 姓氏。
所以基本上我想打印这个:
George|Cameron|Eddy|Cameron //Father-son
George|Cameron|Stephen|Cameron //Father-son
George|Cameron|Lynda|Cameron //Father-daughter
Elisabeth|Cameron|Eddy|Cameron //Mother-son
Elisabeth|Cameron|Stephen|Cameron //Mother-son
Elisabeth|Cameron|Lynda|Cameron //Mother-daughter
etc...
我做了这样的东西:
SELECT
persons.fname, //parents fname => yes, it works
persons.lname, //parents lname => yes, it works
?, //children fname => I have no clue
? //children lname => I have no clue
FROM
persons
INNER JOIN
relationships
ON
persons.id = relationships.parent
我知道我快到了,但我就是不知道该输入什么而不是“?”。 因为,基本上,我需要来自完全相同字段的两次信息,一次是 parents,一次是 children。 但是我如何才能表明我需要前两个参数的 parents 名称和后两个参数的 children 名称(因为它们都是“persons.fname”和“persons.lname")?
PS: 如果能问个最简单直接的方法,让我能学好基础知识,不胜感激
谢谢。
可能最简单的方法是使用 table 别名。
SELECT
parent.fname, //parents fname
parent.lname, //parents lname
children.fname, //children fname
children.lname //children lname
FROM
persons parent
INNER JOIN
relationships
ON
persons.id = relationships.parent
INNER JOIN
persons children
ON relationships.child = children.id
这允许您引用相同的 table 两次,但使用不同的别名,这样您就可以保持它们的正确性。