1

我设置了一些表格来代表不同的产品,因为有些产品与其他产品具有不同的属性。

我正在尝试计算从特定城市列出的项目数量。我的sql语句如下:

Select count(*) as count from location, tbl_books where location.city = tbl_books.location && location.city = 'London' && location.country = 'United Kingdom'

Select count(*) as count from location, tbl_clothes where location.city = tbl_clothes.location && location.city = 'London' && location.country = 'United Kingdom'

这循环计算全国所有城市的结果。这些循环代表内部循环。外循环遍历不同的类别表。

我发现这不是很有效,并且想知道是否有人可以提出任何解决此问题的方法。我正在考虑只创建一个包含城市和类别字段的主表,并在每次从特定城市添加新项目时增加主表中的计数。

4

3 回答 3

1

以下 SQL 查询将通过将 location table.city 键与 tbl_books.location 键连接起来,将 count 和 location.city 值作为一个查询返回。

Select count(*) as count, location.city 
from location, tbl_books 
where location.city = tbl_books.location
group by location.city
于 2012-06-12T20:13:22.357 回答
1

这将按城市总结英国所有城市的所有书籍(在我脑海中,未经测试):

select tbl_books.location, count(tbl_books.location) as count
from location inner join tbl_books on location.city = tbl_books.location
where location.country = 'United Kingdom'
group by tbl_books.location

结果应如下所示:

location  |  count
--------------------
London    |  5
--------------------
Newcastle |  1
--------------------
...       | ...
于 2012-06-12T20:14:17.630 回答
1

这个查询应该给你所有城市和国家的图书数量,不需要循环:

SELECT 
    location.country, 
    location.city,
    COUNT(*) as `count` 
FROM locaton
INNER JOIN tbl_books ON location.city = tbl_books.location 
GROUP BY location.country, location.city
ORDER BY location.country, location.city

结果将如下所示:

country          |   city    |   count
-----------------+-----------+-----------
France           | Paris     |  1
United Kingdom   | Belfast   |  2
United Kingdom   | London    |  3
...
于 2012-06-12T20:16:21.697 回答