[英]MySQL some columns Distinct
我有以下查詢效果很好。
SELECT DISTINCT city,region1,region2 from static_geo_world where country='AU' AND
(city LIKE '%geel%' OR region1 LIKE '%geel%' OR region2 LIKE '%geel%' OR region3 LIKE '%geel%' OR zip LIKE 'geel%') ORDER BY city;
我還需要提取一個名為“id”的列,但這會弄亂 DISTINCT,因為每個 ID 都不同。
我怎樣才能獲得與上面相同的 UNIQUE 記錄集,同時還能獲得每條記錄的“id”? 注意:有時我可以返回幾千條記錄,因此無法查詢每條記錄。
任何想法都會非常受歡迎......
例子:
表可能有以下內容
ID Country zip region1 region2 region3 City
1 AU 3323 geelong victoria Geelong
2 AU 3324 geelong victoria Geelong
3 AU 3325 Geelong North victoria Geelong
我想獲得一組不同的城市、區域 1 和區域 2,因為不同的郵政編碼可能存在重復。 這是當前查詢所做的。 但我也想獲得 ID,因為這是我將作為參考放入所選記錄的數據庫中的內容。
想要的結果:
我希望能夠獲得獨特的 'city,region1,region2
geelong geelong victoria
geelong geelong north victoria
初始查詢得到這些結果
但我也想知道已返回記錄的 ID。 這個 ID 我將在用戶配置文件中使用(存儲在數據庫中)。 例如:
1 geelong geelong victoria
3 geelong geelong north victoria
希望這能更好地解釋它。 只需要包括返回的 Distinct 記錄 ID。
我沒有檢查過這個但是這行不通:
SELECT DISTINCT (city,region1,region2), ID from static_geo_world where country='AU' AND
(city LIKE '%geel%' OR region1 LIKE '%geel%' OR region2 LIKE '%geel%' OR region3 LIKE '%geel%' OR zip LIKE 'geel%') ORDER BY city;
希望這有效!
你不能做你似乎要求的事情:
輸入數據:
ID City Region1 Region2
--- ------ -------- --------
1 geel1 geel2 geel3
2 geel1 geel2 geel3
3 geel4 geel5 geel6
4 geel1 geel2 geel3
查詢select distinct city,region1,region2
返回
City Region1 Region2
------ -------- --------
geel1 geel2 geel3
geel4 geel5 geel6
刪除重復行后,行不再有唯一 ID。 你 state
我怎樣才能獲得與上面相同的 UNIQUE 記錄集,同時獲得每條記錄的“id”
但是對於第一個返回的行,有三個可能的 ID,要求“每條記錄的‘id’”是沒有意義的。
編輯
如果你只是想要最低的 ID,你可以這樣做:
select min(id),city,region1,region2 from ... where ... group by city,region1,region2
改為使用分組依據
SELECT id , city,region1,region2 from static_geo_world where country='AU' AND
(city LIKE '%geel%' OR region1 LIKE '%geel%' OR region2 LIKE '%geel%' OR region3 LIKE '%geel%' OR zip LIKE 'geel%') ORDER BY city group by city;
這將返回您需要的東西。 但是從數據庫記錄中它總是選擇找到的第一條記錄意味着如果 city = 'A' 並且這個城市有很多記錄它會選擇找到的第一條記錄並返回它的 id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.