如何针对同一(外部)表查找两个字段

时间:2014-06-30 09:31:19

标签: mysql sql

(MySQL)我有两张桌子:

|------------|      |------------|
| LOANS      |      |PEOPLE      |
|------------|      |------------|
|lenderID    |      |personID    |
|borrowerID  |      |firstName   |
|LibrarianID |      |lastname    |
|------------|      |------------|

在贷款表中,这些字段的每个人都引用了PEOPLE表中匹配的personID。

我正在寻找的是一个类似

的SQL查询语句
SELECT
   CONCAT(firstName, " ", lastname) as TheLender,
   CONCAT(firstName, " ", lastname) as TheBorrower,
   CONCAT(firstName, " ", lastname) as TheLibrarian,
FROM
   ...
WHERE   
   ...

我无法锻炼如何在一个结果中获得所有三个名字。我如何迭代三个链接,首先是lenderID = personID,然后是borrowerID = personId,然后是librarianID = personID ....一气呵成?

2 个答案:

答案 0 :(得分:0)

你需要多次加入PEOPLE

select 
concat(lend.firstName, " ", lend.lastname) as TheLender,
concat(borr.firstName, " ", borr.lastname) as TheBorrower,
concat(libr.firstName, " ", libr.lastname) as TheLibrarian
from 
LOANS l 
join PEOPLE lend on lend.personID = l.lenderID
join PEOPLE borr on borr.personID = l.borrowerID
join PEOPLE libr on libr.personID = l.LibrarianID
where ....

答案 1 :(得分:0)

SELECT x.Name,y.Name,z.Name FROM 

(SELECT firstName,"",lastname as Name,personID from ... where personID = TheLenderID)as x join(SELECT firstName,"",lastname as Name, personID from ... where personID = TheBorrowerID)as y join(SELECT firstName,"",lastname as Name,personID from ... where personID = TheLibrarianID)as z

这是Microsoft-SQL,但对于mysql,这个想法应该是相同的,你必须为每种类型的人做3个子查询并加入它们。这是我的解决方案,希望它有所帮助。