我设置了几张表来表示不同的产品,因为有些产品与其他产品具有不同的属性。
我正在尝试计算从特定城市列出的项目数量。我的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'
循环计算该国内所有城市的结果。这些循环代表内循环。外部循环遍历不同的类别表。
我发现这不是很有效,并且想知道是否有人能够提出任何解决此问题的方法。我只想创建一个包含城市和类别字段的主表,只需在每次从特定城市添加新项目时增加主表中的计数。
答案 0 :(得分:1)
以下SQL查询将count和location.city值作为一个查询返回,方法是将location table.city键与tbl_books.location键一起使用。
Select count(*) as count, location.city
from location, tbl_books
where location.city = tbl_books.location
group by location.city
答案 1 :(得分: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
--------------------
... | ...
答案 2 :(得分: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
...