4
我試圖查詢MySQL。我有2個表和數據是這樣的:按日期範圍歷史記錄生成完整的類別結構
category_history_structure
+----------------+-----------------+----------+----+-----------+------------+------------+
| category | parent_category | type | id | parent_id | from_date | to_date |
+----------------+-----------------+----------+----+-----------+------------+------------+
| Top level | | category | 1 | 0 | 01.01.2013 | 01.01.2015 |
+----------------+-----------------+----------+----+-----------+------------+------------+
| Category 1 | Top level | category | 2 | 1 | 01.01.2013 | 01.01.2015 |
+----------------+-----------------+----------+----+-----------+------------+------------+
| Category 2 | Top level | category | 3 | 1 | 01.01.2013 | 01.01.2015 |
+----------------+-----------------+----------+----+-----------+------------+------------+
| Sub category 1 | Category 1 | category | 4 | 2 | 01.01.2013 | 01.01.2015 |
+----------------+-----------------+----------+----+-----------+------------+------------+
| Sub category 2 | Category 1 | category | 5 | 2 | 01.01.2013 | 01.03.2013 |
+----------------+-----------------+----------+----+-----------+------------+------------+
| Sub category 2 | Category 2 | category | 5 | 3 | 02.03.2013 | 01.01.2015 |
+----------------+-----------------+----------+----+-----------+------------+------------+
| Product 1 | Sub category 2 | product | 6 | 5 | 01.01.2013 | 01.01.2015 |
+----------------+-----------------+----------+----+-----------+------------+------------+
product_sells
+----+-----------+------+------------+
| id | product | sell | date |
+----+-----------+------+------------+
| 6 | Product 1 | 2 | 01.02.2013 |
+----+-----------+------+------------+
| 6 | Product 1 | 1 | 01.05.2013 |
+----+-----------+------+------------+
| 6 | Product 1 | 3 | 01.06.2013 |
+----+-----------+------+------------+
我需要的日期範圍2013-01-01銷售 - 2015年1月1日,集團按類別。 試圖創建輸出由分類銷售的查詢時,該問題是,「子類別2」被改變那裏的Parent_Category/PARENT_ID並且結果必須是2行爲‘產品1’
結果
+-----------+------------+----------------+-----------+------------+------------+------+
| Top level | Category | Sub category | Product | from_date | to_date | sell |
+-----------+------------+----------------+-----------+------------+------------+------+
| Top level | Category 1 | Sub category 2 | Product 1 | 01.01.2013 | 01.03.2013 | 2 |
+-----------+------------+----------------+-----------+------------+------------+------+
| Top level | Category 2 | Sub category 2 | Product 1 | 02.03.2013 | 01.01.2015 | 4 |
+-----------+------------+----------------+-----------+------------+------------+------+