SQL在一列上查询多列DISTINCT

时间:2013-10-12 13:58:38

标签: mysql sql join

我正在运行一个SQL查询,如下所示,为每个属性选择数据,LEFT JOIN主要从table1('main_table')为每个属性选择数据,如果table2也持有,也在表2中显示数据('houses')每个房产的数据。

但是我想只显示每个属性的结果1。 我在选择的字段之前尝试了DISTINCT的各种结果,但它没有用。

下面是SQL,还显示了返回数据的示例。 例如,128 Mayfield Road在表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

3 个答案:

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

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

大多数数据库都不允许你这样做,因为通常你会关心你得到的其他可能值。

答案 2 :(得分:0)

Distinct将检查所选的所有列是否都是唯一的,而不仅仅是其中一列。

这可能会有所帮助:SQL Group by & Max

相关问题