如果我理解正确,您需要一个结果集,其中每一行都是密码,后跟每种兴趣点的数字。
您指定的目标结果看起来需要是一个很长的自然英文字符串。我不会让你走那么远,但我会给你一些你可以在代码中使用的东西。
这是您最终会得到的最终结果:
pincode | hospitals | temples | masjids | companies | churches | schools
560038 | 2 | 1 | 0 | 0 | 1 | 0
560049 | 0 | 0 | 1 | 1 | 0 | 1
562129 | 0 | 0 | 0 | 0 | 0 | 1
注意:我认为以这种方式要求结果并不理想。如果稍后添加新类型的兴趣点,您将不得不重写查询。但既然是这个问题,那就是答案:
有两种方法可以做到这一点,并且都使用对每种类型的兴趣点执行 count(*) 的子查询。第一个选项是将子查询嵌入到查询的 SELECT 部分。第二种选择是从子查询中创建派生表并将它们连接在一起。
这是选项1:
SELECT
mainTbl.pincode,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 604) as hospitals,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1306) as temples,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1305) as masjids,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1302) as churches,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 204) as schools,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 102) as companies
FROM myTable mainTbl
WHERE mainTbl.city_id = ?
和选项2:
SELECT
mainTbl.pincode,
hospitalsTbl.hospitals,
templesTbl.temples,
masjidsTbl.masjids,
churchesTbl.churches,
schoolsTbl.schools,
companiesTbl.companies
FROM myTable mainTbl
JOIN (SELECT count(*) as hospitals, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 604) hospitalsTbl ON hospitalsTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as temples, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1306) templesTbl ON templesTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as masjids, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1305) masjidsTbl ON masjidsTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as churches, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1302) churchesTbl ON churchesTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as schools, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 204) schoolsTbl ON schoolsTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as companies, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 102) companiesTbl ON companiesTbl.pincode = mainTbl.pincode
WHERE mainTbl.city_id = ?
如您所见,查询非常冗长。最好有这样的东西:
SELECT count(*) as num_poi, poi_id, pincode
FROM myTable
WHERE city_id = ?
GROUP BY poi_id, pincode
然后在代码中构建你的一行行。