简体   繁体   中英

Select data from two rows of the same table

I have a table called TransferRequest with two columns that are (receivingPrison, currentPrison). They both reference a table Prison with columns (prisonID, location). I need to have some sort of join to display the 'location' of both prison eg. Result: "Washington", "New York". I know to get the location from one table I can do:

SELECT Prison.location  
FROM Prison
JOIN TransferRequest
ON Prison.prisonID = TransferRequest.currentPrison;

And:

SELECT Prison.location  
FROM Prison
JOIN TransferRequest
ON Prison.prisonID = TransferRequest.receivingPrison;

But I'm not sure how to do a SELECT for two of the same type of items from the same type of table. What would I do to get this table? (Headers: Current Location, Receiving Location).

Maybe I'm missing something but if you just want to get the location names for the current and receiving prisons you could get them by joining the prison table twice:

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;

Sample SQL Fiddle

A correlated subquery could do it:

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;

You can use this:

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'

See this here-> http://sqlfiddle.com/#!3/9aac5/9

Hope this helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM