我如何计算每个地址的商店数量?

时间:2015-09-30 19:18:53

标签: mysql join

我有一个查询,查找具有重复街道名称的行:

SELECT a.id, a.street1, a.postal_code, a.fk_countryID
FROM address a
INNER JOIN (
  SELECT b.street1, b.postal_code, b.fk_countryID
  FROM address b
  GROUP BY b.street1, b.postal_code
  HAVING count(b.id) > 1
) duplicate ON a.street1 = duplicate.street1 
AND a.postal_code = duplicate.postal_code
AND a.fk_countryID = duplicate.fk_countryID
ORDER BY a.street1, a.postal_code 

结果是(忽略NumStores列):

+-------+-----------------+------------+------+-----+-----------+
| id    | street          | postalCode | city | CC  | NumStores |
+-------+-----------------+------------+------+-----+-----------+
| 11101 | Bogstadveien 36 | 0366       | Oslo | NO  |     ?     |
| 11102 | Bogstadveien 36 | 0366       | Oslo | NO  |     ?     |
| 11103 | Bogstadveien 36 | 0366       | Oslo | NO  |     ?     |
+---------------------------------------------------+-----------+

目标是删除重复的行。为了完成这项工作,我需要查看实际使用每个地址的商店数量。 0计数我可以立即删除。有一个或多个的我必须"移动"到删除之前要使用的地址。这都是通过GUI(JS / PHP)手动完成的。

所以问题是;如何为每行添加商店数量?

2 个答案:

答案 0 :(得分:1)

我终于找到了有用的东西。

SELECT a.id, a.street1, a.postal_code, a.fk_countryID, COUNT(c.fk_addressID) as NumStores
(...)
LEFT JOIN store c
ON a.id = c.fk_addressID
GROUP BY a.id
ORDER BY a.street1, a.postal_code; 

结果是:

+-------+-----------------+------------+------+-----+-----------+
| id    | street          | postalCode | city | CC  | NumStores |
+-------+-----------------+------------+------+-----+-----------+
| 11101 | Bogstadveien 36 | 0366       | Oslo | NO  |     0     |
| 11102 | Bogstadveien 36 | 0366       | Oslo | NO  |     0     |
| 11103 | Bogstadveien 36 | 0366       | Oslo | NO  |     3     |
+---------------------------------------------------+-----------+

答案 1 :(得分:0)

我会编写一个子查询来使用这样的简单聚合来获取每个地址的存储计数:

SELECT address, COUNT(*) AS numStores
FROM storeTable
GROUP BY address;

看看你的问题,这里可能会有一个联接,因为你没有在商店表中保留地址,所以我把它简化为只展示你将如何得到它。然后,你将它加入到你的另一个表中:

SELECT stuff, tmp.numStores
FROM stuffTables
JOIN(
   SELECT address, COUNT(*) AS numStores
   FROM storeTable
   GROUP BY address) tmp ON tmp.address = stuffTables.address;