SQL Join没有找到记录

时间:2014-08-25 07:06:12

标签: sql sql-server self-join

所以我试图只使用一个有多个选择的表进行连接。

我正在使用的表格看起来像这样......

    Floor No. | Apartment No. | Bathroom No. | Size
        1     |       1       |       1      |  30
        1     |       1       |       2      |  20
        1     |       2       |       1      |  30
        1     |       2       |       2      |  40
        1     |       2       |       3      |  60
        2     |       1       |       1      |  30
        2     |       1       |       2      |  20
        2     |       2       |       1      |  30
        2     |       2       |       2      |  40
        2     |       2       |       3      |  60

基本上,每层楼都有许多公寓,每间公寓都有许多不同大小的浴室。我试图返回看起来像这样的结果..

    Floor No. | APT1A | APT1B | APT2A | APT2B | APT2C
       1      |   30  |   20  |   30  |   40  |   60
       2      |   30  |   20  |   30  |   40  |   60

到目前为止,我已经得到了这个有效的SQL语句..

    SELECT DISTINCT A.FloorNumber, B.Size As APT1A, C.Size AS APT1B 
    FROM BathroomTable A
    inner join BathroomTable B on a.FloorNumber  = B.FloorNumber
    inner outer join BathroomTable C on a.FloorNumber = C.FloorNumber
    WHERE b.ApartmentNumber = 'APT1' AND b.BathroomNumber = 1
    AND (C.ApartmentNumber = 'APT1' AND C.BathroomNumber = 2)

等等连接,只要我加入数据库中存在的记录就可以工作。但是,有时公寓1中只有一个浴室,而sql查询会尝试查找数据对于第二个浴室,然后将不会返回任何结果。如果找不到空值,有没有办法插入空值?

谢谢,我希望你能理解我正在做的事情。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT DISTINCT B.FloorNumber, B.Size As APT1A, C.Size AS APT1B 
FROM ApartementTable A
inner join BathroomTable B on a.ApartmentNumber  = B.ApartmentNumber AND b.BathroomNumber = 1
LEFT join BathroomTable C on a.ApartmentNumber = C.ApartmentNumber AND C.BathroomNumber = 2
WHERE A.ApartmentNumber = 'APT1' 

答案 1 :(得分:0)

SELECT DISTINCT A.FloorNumber, B.Size As APT1A, C.Size AS APT1B 
FROM BathroomTable A
OUTER join BathroomTable B on a.FloorNumber  = B.FloorNumber
OUTER join BathroomTable C on a.FloorNumber = C.FloorNumber
WHERE b.ApartmentNumber = 'APT1' AND b.BathroomNumber = 1 AND (C.ApartmentNumber = 'APT1' AND C.BathroomNumber = 2)