2014-02-20 60 views
0

我有兩個表。城市,地方。在單個mysql查詢中查找計數和數據

Cities: 
    id | name 
Localities: 
    id | city_id | name 

我可以做一個單一的查詢來獲取城市(每個城市只有10行)的地區名單,也該城地區的計數?

我知道我可以在2個不同的查詢中做到這一點。

請建議是否可以使用Django查詢集完成。

型號:

class City(models.Model): 
    name = models.CharField(max_length=200)  

class Locality(models.Model): 
    name = models.CharField(max_length=200) 
    city = models.ForeignKey(City,related_name='LocalityCity') 
+0

什麼是你的結果應該是什麼樣子的?每個地方顯示一列中的計數?每個地方一行加一行顯示計數?每個城市一行顯示地點和數量? –

+0

每個城市10個地方的實際城市數量。例如。 'city1,locality1,13','city1,locality2,13','city1,locality3,13' ...直到'city1,locality10,13',然後'city2,locality14,8'直到'city2,所有城市的地方15,8'等等。 – Anuj

回答

0
select * from 
(select c.id as city_id, count(l.id) as "localities count per city" 
    from cities as c 
    inner join localities as l on l.city_id = c.id) as localities_count_per_city 
inner join 
(select c.id as city_id, c.name, l.name 
    from cities as c 
    inner join localities as l on l.city_id = c.id 
    limit 10) as localities_per_city) as localities_per_city 
on localities_count_per_city.city_id = localities_per_city.city_id 

這應該加入每個城市的各個地方數與城市行各地方。

0

你應該提到模型而不是SQL表模式。這裏是你如何對它們進行查詢:

cities = City.objects.annotate(num_cities=Count("locality")) 
for city in cities: 
    print(city.locality_set, city_num_cities) 
+0

我認爲這是相當可預測的SQL模式。順便說一句,你是如何獲得當地設置? – Anuj

+0

反向關係是由Django創建的,默認情況下是https://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects – arocks

0

我可以做一個單一的查詢來獲取 城市(每個城市只有10行)的地區名單,各地也計數在 那個城市?

假設你的機型有:

class Locality(models.Model): 
    name = models.CharField(max_length=200)  

class City(models.Model): 
    name = models.CharField(max_length=200) 
    locality = models.ManyToMany(Locality) 

你可以得到你的結果是這樣的:

all_cities = City.object.all() 
for city in all_cities: 
    print('City: {} Total Localities: {}'.format(city.name, city.locality_set.count())) 
    for loc in city.locality_set.all(): 
     print('\t{}'.format(loc.name)) 

在上面的代碼中,有查詢被執行 - 但Django的查詢集被緩存,所以您可以放心,每次都會執行正確的查詢。

如果你想獲得它在做一次,那麼你需要使用聚集:

from django.db.models import Count 

all_cities = City.objects.all().annotate(localities=Count('locality')) 
for city in all_cities: 
    print('City: {} Total Localities: {}'.format(city, city.localities)) 
+0

你能否根據我提到的模型改正你的答案? – Anuj

+0

試試看看你是否可以爲自己做到這一點,如果遇到問題;然後問。 –