SQL 将相同 table 中相同列中的 return 数据连接到结果中的两个不同行(星球大战示例)
SQL Join to return data from The Same Column in the same table to two diffrent rows in result (Star Wars Example)
关于连接表的新手问题。我想从 SQL 语句中的列 TWICE 中检索名称,我在圈子里 运行。
我有两个 Tables - “公司”和“人员”
Table-“人物”
ID
Name
Phone
1
Luke
555-1212
2
Leia
555-1234
3
Han
999-8888
4
Anikin
888-9876
5
Obi-wan
555-1212
6
R2-D2
#% - **!?
Table - “公司”
ID
CompanyName
PrimaryContact
AltContact
1
Speeders R Us
5
1
2
Droid Repair World
6
4
3
Luke's Second Hand Store
1
4
4
Cloak World
4
5
5
Ye Old Blaster Shoppe
3
2
如果我想获得同时提供公司联系人姓名的结果,我该怎么做?
我可以让 PrimaryContact 正确地使用诸如...
SELECT C.*, P.Name as 'Primary'
FROM `Company` C
Join People P on
C.PrimaryContact = P.ID
WHERE C.ID =3
成功returns
ID
CompanyName
PrimaryContact
AltContact
Primary
3
Luke's Second Hand Store
1
4
Luke
但对于我来说,我无法弄清楚如何将此 SQL 修改为也 return“Anikin”作为备用联系人。这是 UNION 语句有用的示例吗?
您可以多次加入同一个 table,每次只需输入一个新别名即可。
Join People P on C.PrimaryContact = P.ID
Join People P1 on C.AltContact = P1.ID
Join People altcontact on C.AltContact = altcontact.ID
Join People P256 on C.yetanotheralternateContact = P256.ID
您需要加入另一个人的每个联系人 table
SELECT C.ID,C.CompanyName, P.Name as 'Primary' , P.Phone As 'primary_Phone', P2.Name on 'Alternative', P2.Phone as 'Alternatibe_Phone
FROM `Company` C
Join People P on
C.PrimaryContact = P.ID
Join People P2 on
C.AltContact = P2.ID
WHERE C.ID
关于连接表的新手问题。我想从 SQL 语句中的列 TWICE 中检索名称,我在圈子里 运行。
我有两个 Tables - “公司”和“人员”
Table-“人物”
ID | Name | Phone |
---|---|---|
1 | Luke | 555-1212 |
2 | Leia | 555-1234 |
3 | Han | 999-8888 |
4 | Anikin | 888-9876 |
5 | Obi-wan | 555-1212 |
6 | R2-D2 | #% - **!? |
Table - “公司”
ID | CompanyName | PrimaryContact | AltContact |
---|---|---|---|
1 | Speeders R Us | 5 | 1 |
2 | Droid Repair World | 6 | 4 |
3 | Luke's Second Hand Store | 1 | 4 |
4 | Cloak World | 4 | 5 |
5 | Ye Old Blaster Shoppe | 3 | 2 |
如果我想获得同时提供公司联系人姓名的结果,我该怎么做?
我可以让 PrimaryContact 正确地使用诸如...
SELECT C.*, P.Name as 'Primary'
FROM `Company` C
Join People P on
C.PrimaryContact = P.ID
WHERE C.ID =3
成功returns
ID | CompanyName | PrimaryContact | AltContact | Primary |
---|---|---|---|---|
3 | Luke's Second Hand Store | 1 | 4 | Luke |
但对于我来说,我无法弄清楚如何将此 SQL 修改为也 return“Anikin”作为备用联系人。这是 UNION 语句有用的示例吗?
您可以多次加入同一个 table,每次只需输入一个新别名即可。
Join People P on C.PrimaryContact = P.ID
Join People P1 on C.AltContact = P1.ID
Join People altcontact on C.AltContact = altcontact.ID
Join People P256 on C.yetanotheralternateContact = P256.ID
您需要加入另一个人的每个联系人 table
SELECT C.ID,C.CompanyName, P.Name as 'Primary' , P.Phone As 'primary_Phone', P2.Name on 'Alternative', P2.Phone as 'Alternatibe_Phone
FROM `Company` C
Join People P on
C.PrimaryContact = P.ID
Join People P2 on
C.AltContact = P2.ID
WHERE C.ID