我有一个名为TransferRequest的表,其中有两列是(receivingPrison,currentPrison)。他们都引用一个表监狱与列(prisonID,位置)。 我需要进行某种联接才能显示“地点”。两个监狱,例如。结果:"华盛顿","纽约"。 我知道我可以从一张桌子上获取位置:
SELECT Prison.location
FROM Prison
JOIN TransferRequest
ON Prison.prisonID = TransferRequest.currentPrison;
和
SELECT Prison.location
FROM Prison
JOIN TransferRequest
ON Prison.prisonID = TransferRequest.receivingPrison;
但是我不确定如何对同一类型的表中的两个相同类型的项执行SELECT。得到这张桌子怎么办? (标题:当前位置,接收位置)。
答案 0 :(得分:1)
也许我错过了一些东西,但是如果你只想获得当前和接收监狱的位置名称,你可以通过加入prison
表两次获得它们:
SELECT
rec_prison.location as 'Recieving Location',
cur_prison.location as 'Current Location'
FROM TransferRequest tr
INNER JOIN Prison rec_prison
ON rec_prison.prisonID = tr.receivingPrison
INNER JOIN Prison cur_prison
ON cur_prison.prisonID = tr.currentPrison;
答案 1 :(得分:0)
相关的子查询可以做到:
SELECT P1.location AS location1
, (SELECT Prison.location
FROM Prison
JOIN TransferRequest
ON Prison.prisonID = TransferRequest.receivingPrison ) AS location2
FROM Prison P1
JOIN TransferRequest T1
ON P1.prisonID = T1.currentPrison;
答案 2 :(得分:0)
您可以使用:
SELECT (SELECT prison.Location
FROM TransferRequest tr
INNER JOIN Prison prison ON tr.reciveingPrisonID = prison.prisonID
WHERE tr.reciveingPrisonID = 1) AS'Recieving Location',
(SELECT prison.Location
FROM TransferRequest tr
INNER JOIN Prison prison ON tr.currentPrisonID = prison.prisonID
WHERE tr.currentPrisonID = 4) as 'Current Location'
在此处查看 - > http://sqlfiddle.com/#!3/9aac5/9
希望这有帮助!!!