简体   繁体   中英

Count DISTINCT multiple mysql rows query

I insert data in mysql table row using multiple method : 1#2#3 . 1 is ID of country, 2 is Id of state, 3 is ID of town . now i have this table for real estate listings. for each list(home) i have country/state/town (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 :

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

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?
  • Your "selector" columns in your other tables are badly named. What are they? Are they foreign key references to ids in other tables? 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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