簡體   English   中英

SQL查詢一列上的多列DISTINCT

[英]SQL query multiple columns DISTINCT on one column

我正在運行如下的SQL查詢,使用左聯接選擇每個屬性的數據,主要是從每個屬性的表1('main_table')中選擇數據,如果表2還包含每個屬性的數據,則還顯示表2('houses')中的數據屬性。

但是,我只希望每個屬性顯示結果1。 在我選擇的字段之前,我已經使用DISTINCT嘗試了各種結果,但沒有成功。

下面是SQL,還顯示了返回數據的示例。 例如,Mayfield Road 128在表2中有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

也許是這樣嗎?

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

假設一所房子有多個入口。 如果您不在乎在其他列中獲得哪些可能的值,則可以使用惡意得多的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

大多數數據庫都不允許您這樣做,因為通常您會在意其他哪些可能的值。

Distinct將檢查所有選定的列是否都是唯一的,而不僅僅是其中之一。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM