简体   繁体   English

计数DISTINCT多个mysql行查询

[英]Count DISTINCT multiple mysql rows query

I insert data in mysql table row using multiple method : 1#2#3 . 我使用多种方法在mysql表行中插入数据:1#2#3。 1 is ID of country, 2 is Id of state, 3 is ID of town . 1是国家的ID,2是州的ID,3是镇的ID。 now i have this table for real estate listings. 现在我有这张桌子用于房地产清单。 for each list(home) i have country/state/town (1#2#3). 对于每个列表(家),我都有国家/州/镇(1#2#3)。 in country table i have list of country - in country table i have list of state - in country table i have list of town. 在国家表中,我有国家列表-在国家表中,我有州列表-在国家表中,我有镇列表。 i need to The number of houses in country / state / town . 我需要国家/州/镇的房屋数量。 me mean is : 我的意思是:

USA [ 13 ] <!-- This Is equal of alabama+alaska+arizona -->
----Alabama [8] <!-- This Is equal of Adamsville+Addison+Akron -->
-------Adamsville [2]
-------Addison[5]
-------Akron[1] 
......(list of other City)
----Alaska [ 3 ]
-------Avondale[3]
......(list of other City)
----Arizona [ 2 ]
-------College[2]
......(list of other City)

Lisintg Table : Lisintg表:

ID -- NAME -- LOCATION -- DATEJOIN -- ACTIVE
 1 -- TEST -- 1#2#3    -- 20110101 -- 1
 2 -- TEST1 -- 1#2#3    -- 20110101 -- 1
 3 -- TEST2 -- 1#3#5    -- 20110101 -- 1
 4 -- TEST3 -- 1#7#6    -- 20110101 -- 1

Country Table : 国家表:

 id       -- name  
 1        -- USA  

stats Table : 统计资料表:

id        -- countryid -- name  
 1        -- 1         -- albama
 2        -- 1         -- alaska
 3        -- 1         -- akron

town Table : 城镇表:

id        -- countryid -- statsid   -- name  
 1        -- 1         -- 1         -- adamsville
 2        -- 1         -- 1         -- addison 
 3        -- 1         -- 1         -- akron

Thanks For Any Help. 谢谢你的帮助。

I don't know your table schema, but you can try: 我不知道您的表架构,但是您可以尝试:

SELECT count(DISTINCT country_name) FROM `tbl_country`

count() function will return number of row count()函数将返回行数

I don't think your schema is ideal and you should look at changing it. 我认为您的架构不是理想的,您应该考虑对其进行更改。

  • Your location field in the listings table is doing more than one thing. 列表表中的您的位置字段正在做很多事情。 Maybe it should just store the town ID as surely you can work out the state and country from that? 也许它应该只存储城镇ID,以确保您可以从中得出州和国家/地区?
  • Your "selector" columns in your other tables are badly named. 您在其他表中的“选择器”列命名错误。 What are they? 这些是什么? Are they foreign key references to ids in other tables? 它们是其他表中对ID的外键引用吗? If so, name them as such. 如果是这样,请这样命名。

So I think what you are trying to achieve is a sum of all distinct listings in each geographical area. 因此,我认为您想要实现的是每个地理区域中所有不同列表的总和。 If so you should look into SELECT...GROUP BY . 如果是这样,您应该查看SELECT ... GROUP BY Something like this 像这样

SELECT location,count(*)
FROM listings
GROUP BY location

This would give you a list of each distinct location and how many times it appears in the listings table. 这将为您提供每个不同位置的列表以及它在列表中出现的次数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM