[英]SQL query multiple columns DISTINCT on one column
I am running an SQL query as below, selecting data for each property with a LEFT JOIN selecting data mainly from table1 ('main_table') for each property and also displaying data in table 2('houses') if table2 also holds data on each property. 我正在运行如下的SQL查询,使用左联接选择每个属性的数据,主要是从每个属性的表1('main_table')中选择数据,如果表2还包含每个属性的数据,则还显示表2('houses')中的数据属性。
However I want to only show results 1 per property. 但是,我只希望每个属性显示结果1。 I have tried various results with DISTINCT before the fields that i am selecting but it hasn't worked.
在我选择的字段之前,我已经使用DISTINCT尝试了各种结果,但没有成功。
Below is the SQL and also showing a sample of the data returned. 下面是SQL,还显示了返回数据的示例。 So for example, 128 Mayfield Road has 2 entries in table 2 so it is returned twice but i only want to show each house once.
例如,Mayfield Road 128在表2中有2个条目,因此它被返回了两次,但我只想显示每个房子一次。
Many Thanks 非常感谢
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
Maybe like this? 也许是这样吗?
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
Say a house has more than one entry. 假设一所房子有多个入口。 If you don't care which of the possible values you get in the other columns then you can use a much maligned MySQL extension to group by:
如果您不在乎在其他列中获得哪些可能的值,则可以使用恶意得多的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
Most databases won't let you do this, because usually you do care which of the other possible values you get. 大多数数据库都不允许您这样做,因为通常您会在意其他哪些可能的值。
Distinct will check that all columns being selected are unique, not just one of them. Distinct将检查所有选定的列是否都是唯一的,而不仅仅是其中之一。
This might be helpful: SQL Group by & Max 这可能会有所帮助: SQL Group by&Max
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.