2013-10-12 94 views
0

我正在運行SQL查詢,如下所示,爲每個屬性選擇具有LEFT JOIN的數據,主要從table1('main_table')爲每個屬性選擇數據,並在表2中顯示數據( '房屋'),如果table2也持有每個房產的數據。SQL查詢多列DISTINCT在一列

但是,我想只顯示結果1每個屬性。 我試過各種結果與DISTINCT之前,我選擇的領域,但它沒有奏效。

下面是SQL並顯示返回的數據的示例。 因此,例如,梅菲爾德路128號在表2中有兩個條目,所以它返回兩次,但我只想顯示每個房子一次。

非常感謝

SELECT main_table.housenumber, main_table.streetname, main_table.rent, houses.houseID, houses.path, houses.rooms 
FROM main_table 
LEFT JOIN houses ON main_table.housenumber = houses.housenumber 
AND main_table.streetname = houses.streetname 

533 Portswood Road 57 NULL NULL       NULL 
35 Ripstone Gardens 70 NULL NULL       NULL 
67 Kent Road  68 NULL NULL       NULL 
21 Bealing Close 65 NULL NULL       NULL 
75 Broadlands Road 76 NULL NULL       NULL 
7 Gordon Avenue 70 243  images_housing/GOR1.jpg   4 
29 Broadlands Road 74 NULL NULL       NULL 
10 Westbrook Way 65 NULL NULL       NULL 
328C Burgess Road  85 NULL NULL       NULL 
10 Thackeray Road 68 NULL NULL       NULL 
128 Mayfield Road 70 311  images_housing/mayfield1.jpg 4 
128 Mayfield Road 67 311  images_housing/mayfield1.jpg 4 
+0

什麼是你需要準確地當房子記錄是重複? FIFO記錄還是LIFO記錄? –

回答

0

也許這樣嗎?

SELECT 
    main_table.housenumber, 
    main_table.streetname, 
    max(main_table.rent) 
    houses.houseID, 
    houses.path, 
    houses.rooms 
FROM main_table 
LEFT JOIN houses ON main_table.housenumber = houses.housenumber 
AND main_table.streetname = houses.streetname 
group by 
    main_table.housenumber, 
    main_table.streetname, 
    houses.houseID, 
    houses.path, 
    houses.rooms 
0

說一個房子有多個條目。如果你不關心你在其他列中獲得的可能值,那麼你可以通過使用洪水猛獸MySQL擴展到組:

Select 
    m.housenumber, 
    m.streetname, 
    m.rent, 
    h.houseID, 
    h.path, 
    h.rooms 
From 
    main_table m 
     Left Join 
    houses h 
     on m.housenumber = h.housenumber and 
      m.streetname = h.streetname 
Group By 
    m.housenumber, 
    m.streetname 

大多數數據庫不會讓你這樣做,因爲通常你確實關心你獲得的其他可能的價值。

0

獨特將檢查所選擇的所有列是唯一的,而不僅僅是其中之一。

這可能會幫助你:SQL Group by & Max