0

假设您有一个包含两个(或更多)列的表,这些列链接到另一个表:

 house_history         houses
---------------       --------
OwnerID               HouseID
PreviousHouseID       Address
CurrentHouseID

并且您想从这些 ID 中的每一个返回数据:

---------------------------------------------------------------
|OwnerID|        PreviousAddress    |      CurrentAddress     |
---------------------------------------------------------------
         (linked to PreviousHouseID) (linked to CurrentHouseID)

你会怎么做呢?(特别是我对使用 MySQL 很感兴趣)

4

3 回答 3

1
SELECT OwnerId, p.Address as PreviousAddress, c.Address as CurrentAddress
FROM house_history h
LEFT JOIN houses p ON h.PreviousHouseID = p.HouseID
LEFT JOIN houses c ON h.CurrentHouseID = c.HouseID 
于 2012-05-15T20:11:25.243 回答
1

尝试这个

SELECT hh.OwnerID,h1.Address,h2.Address
FROM house_history hh 
LEFT JOIN house h1 ON h1.HouseId = hh.PreviousHouseID
LEFT JOIN house h2 ON h2.HouseId = hh.CurrentHouseID

可能您可能需要INNER JOIN的LEFT JOIN,因为它在当前和以前的房子为空时也有效

于 2012-05-15T20:11:32.720 回答
0
SELECT
    house_history.OwnerID
    , houses_previous.Address AS PreviousAddress
    , houses_current.houses.Address AS CurrentAddress
FROM house_history
    LEFT JOIN houses AS houses_current ON (house_history.CurrentHouseID = houses_current.HouseID)
    LEFT JOIN houses AS houses_previous ON (house_history.PreviousHouseID = houses_previous.HouseID);
于 2012-05-15T20:14:22.220 回答