下面是我正在使用的4个表的示例。
Items
+----+------+
| id | name |
+----+------+
| 1 | abc |
| 2 | def |
| 3 | ghi |
+----+------+
Buy Table
+----+-------------+-----+---------+
| id | date | qty | item_id |
+----+-------------+-----+---------+
| 1 | 2020-05-01 | 10 | 1 |
| 2 | 2020-05-02 | 20 | 2 |
| 3 | 2020-05-03 | 5 | 3 |
+----+-----------+-------+---------+
Rent Table
+----+-------------+-----+---------+
| id | date | qty | item_id |
+----+-------------+-----+---------+
| 1 | 2020-05-02 | 5 | 2 |
| 2 | 2020-05-03 | 10 | 2 |
| 3 | 2020-05-04 | 15 | 3 |
+----+-----------+-------+---------+
Sell Table
+----+-------------+-----+---------+
| id | date | qty | item_id |
+----+-------------+-----+---------+
| 1 | 2020-05-03 | 10 | 1 |
| 2 | 2020-05-05 | 20 | 3 |
| 3 | 2020-05-06 | 5 | 3 |
+----+-----------+-------+---------+
我正在尝试用php foreach获取输出,比如这样的东西。。。
In case item_id "1"
+-------------+--------------+---------------+---------------+------+
| date | BUY SUM(qty) | RENT SUM(qty) | SELL SUM(qty) | Name |
+-------------+--------------+---------------+---------------+------+
| 2020-05-01 | 10 | 0 | 0 | abc |
| 2020-05-02 | 0 | 0 | 0 | abc |
| 2020-05-03 | 0 | 0 | 10 | abc |
| 2020-05-04 | 0 | 0 | 0 | abc |
| 2020-05-05 | 0 | 0 | 0 | abc |
| 2020-05-06 | 0 | 0 | 0 | abc |
+-------------+--------------+---------------+---------------+------+
这是我来查询的一个表。。。
SELECT date AS date,
SUM(qty) AS qty
FROM buy_table
WHERE item_id='1'
AND MONTH(date)=MONTH(CURDATE())
GROUP BY DATE(date)
1条答案
按热度按时间rbl8hiat1#
你可以
cross join
这个item
s桌上有所有可用的date
其他三个表中的,然后三个表中的聚合left join
学生: