0

我正在运行如下 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
4

3 回答 3

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
于 2013-10-12T14:06:18.483 回答
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

大多数数据库不会让您这样做,因为通常您确实关心您获得的其他可能值中的哪一个。

于 2013-10-12T14:07:17.577 回答
0

Distinct 将检查所有被选择的列是唯一的,而不仅仅是其中一个。

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

于 2013-10-12T14:12:21.600 回答