查表 [ member as m ] 的数据总量 [ count(*) as total ] 顺带一起展示 city 表的 [ c.id,c.city_name,c.pinyin ] 关联另外一张表 [ left join city as c ] 关系是 member 的 m.from 关联 city 的 c.pinyin [ on m.from=c.pinyin ] 按照 c.pinyin 分组 [ group by c.pinyin ] 按照 total 降序排列 [ order by total desc ]
自己测试过以下语句 select c.id,c.city_name,c.pinyin,count(*) as total from `city` as c left join `member` as m on m.from = c.pinyin group by c.pinyin order by total desc 空记录的深圳本该是 0 ,但是查出来竟然是 1 。
select c.id,c.city_name,c.pinyin,count(*) as total from `city` as c left join `member` as m on m.from = c.pinyin group by c.id order by total desc 空记录的深圳本该是 0 ,但是查出来竟然是 1 。
select c.id,c.city_name,c.pinyin,count(*) as total from `city` as c left join `member` as m on m.from = c.pinyin group by c.city_name order by total desc 空记录的深圳本该是 0 ,但是查出来竟然是 1 。
select c.id,c.city_name,c.pinyin,count(*) as total from `member` as m left join `city` as c on m.from = c.pinyin group by m.from order by total desc 少了 0 数据的深圳,数据不全。
select c.id,c.city_name,c.pinyin,count(*) as total from `member` as m left join `city` as c on m.from = c.pinyin group by c.city_name order by total desc 少了 0 数据的深圳,数据不全。
select c.id,c.city_name,c.pinyin,count(*) as total from `member` as m left join `city` as c on m.from = c.pinyin group by c.pinyin order by total desc 少了 0 数据的深圳,数据不全。
跟 city 相关的信息都放 city 表,和 member 的关联只给一个 city_id 。 统计的时候 city 做主表,连上 member , count 一下就好。
alex321
2015-12-08 21:41:19 +08:00
SELECT `member`.*,`city`.*,count(`member`.id) AS total FROM member RIGHT JOIN city ON `member`.`from`=`city`.`pinyin` GROUP BY `city`.`id` ORDER BY total DESC
你要统计的是按照城市来,请使用 right join 。。
jookr
2015-12-08 21:47:56 +08:00
原来如此 谢谢各位 看来得重温 mysql 基础知识了
soolby
2015-12-24 12:19:33 +08:00
过来问问楼主你还健身吗?
第 1 页 / 共 1 页
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。