【发布时间】:2018-09-01 11:26:05
【问题描述】:
我有下面五个表格,如果可能的话,我想通过使用一个 mysql 查询来显示每个国家、州、城市和地区的销售额:
注意:如果州、市、区没有销售,那么我需要查询结果显示0或空白(即使没有销售也必须显示州、城市、地区名称)特定的州、市或区)
+------------+----------+
| country |
+------------+----------+
| country_id | country |
+------------+----------+
| 1 | country1 |
| 2 | country2 |
+------------+----------+
+----------------+--------+------------+
| state_province |
+----------------+--------+------------+
| state_id | state | country_id |
+----------------+--------+------------+
| 1 | state1 | 1 |
| 2 | state1 | 2 |
| 3 | state2 | 2 |
| 4 | state2 | 1 |
+----------------+--------+------------+
+---------+-------+----------+
| city |
+---------+-------+----------+
| city_id | city | state_id |
+---------+-------+----------+
| 1 | city1 | 1 |
| 2 | city2 | 1 |
| 3 | city1 | 3 |
| 4 | city2 | 3 |
| 5 | city1 | 4 |
| 6 | city2 | 4 |
+---------+-------+----------+
请注意,国家 (country_id = 2) 中的州 (state_id =2) 在上表中没有城市。
+-------------+-----------+---------+
| district |
+-------------+-----------+---------+
| district_id | district | city_id |
+-------------+-----------+---------+
| 1 | district1 | 1 |
| 2 | district2 | 1 |
| 3 | district1 | 2 |
| 4 | district2 | 2 |
| 5 | district1 | 4 |
| 6 | district2 | 4 |
| 7 | district1 | 5 |
| 8 | district1 | 6 |
+-------------+-----------+---------+
+----------+------------+----------+---------+-------------+--------+
| sales |
+----------+------------+----------+---------+-------------+--------+
| sales_id | country_id | state_id | city_id | district_id | amount |
+----------+------------+----------+---------+-------------+--------+
| 1 | 1 | 0 | 0 | 0 | 1000 |
| 2 | 1 | 0 | 0 | 0 | 2000 |
| 3 | 1 | 1 | 0 | 0 | 300 |
| 4 | 1 | 1 | 0 | 0 | 70 |
| 5 | 1 | 1 | 1 | 0 | 50 |
| 6 | 1 | 1 | 1 | 1 | 25 |
| 7 | 1 | 4 | 1 | 1 | 25 |
| 8 | 1 | 4 | 5 | 0 | 25 |
| 9 | 2 | 0 | 0 | 0 | 3000 |
| 10 | 2 | 0 | 0 | 0 | 500 |
| 11 | 2 | 3 | 0 | 0 | 300 |
| 12 | 2 | 3 | 4 | 6 | 70 |
+----------+------------+----------+---------+-------------+--------+
谢谢
【问题讨论】:
-
你尝试过什么吗?
-
您的问题 .. 不清楚 .. 显示您的预期。结果 .. 和 Strawberry 所问的 .. 您尝试过的查询 ..
-
请记住,SO 不是代码编写服务。我们很高兴帮助您解决代码问题,但您至少必须展示您尝试过的内容,以及您无法克服的错误或问题。
-
不知道为什么scaisEdge这个问题不清楚?我设法通过使用类似于以下的查询来显示区域表的结果(销售总和):SELECT *, country.country_id, state.state_id, district.district_id, SUM(sales.amount) as the_sum FROM district JOIN sales ON sales.country_id =country.country_id AND sales.state_id=state.state_id AND sales.city_id=city.city_id AND sales.district_id=district.district_id group by district_id order by state_id,city_id,district_id
-
来自
tsql标签的描述:“不要将此标签用于MySQL、PostgreSql、Oracle(Pl/SQL)相关查询。”也不清楚php和mysqli与这个问题有什么关系。