0

我真的不知道如何为这个问题提出一个具体的问题,所以我会尽力解释这个场景

有问题的表具有以下列。

**Table#1 Patients**
-PatID
-Name
-Guarantor FK_PatID (Refer to Patients Table)

好的,假设我想从单个 SQL 查询中选择表中的患者姓名和他的担保人姓名。

SELECT p.Name, p.Guarantor
FROM Patients P

该语句将获取患者姓名和担保人的 PatID,但如何匹配该担保人的 ID 以在同一 SQL 语句中获取其姓名?

4

3 回答 3

5

你可以加入一个表本身

SELECT P.Name, P.Guarantor, P2.Name
FROM Patients P
INNER JOIN Paitents P2 on P2.PatId = P.Guarantor
于 2013-05-08T20:37:43.960 回答
0

这是SELF JOIN的经典示例

SELECT 
P1.Name, 
P1.Guarantor+ 'is Guarantor of' +P2.Name
FROM Patients P1
INNER JOIN Paitents P2 on P2.PatId = P1.Guarantor

类似的堆栈溢出问题

于 2013-05-08T20:47:02.377 回答
-1
Select p.name from Patients p where
p.guarantor in (select p1.guarantor from patients p1 where name = 'foo')

这将为您提供所有名为foo的患者的担保人的姓名。您只需在另一个查询的 where 子句中使用一个查询。

于 2013-05-08T20:39:22.053 回答