具有多个查找的条件别名

时间:2012-05-15 20:05:52

标签: mysql sql

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

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

并且您希望从每个ID中返回数据:

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

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

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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

您可能需要 LEFT JOIN 而不是 INNER JOIN ,因为当当前和上一个房子为空时它也可以使用

答案 2 :(得分: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);