如何创建视图( producer_view 和 retailer_view ),以显示每个交易 SUM( unit_price * quantity )
时的总金额>供应商和客户?
producer_view
+------+-------------------+-----------------+
| name | as_supplier_total | as_client_total |
+------+-------------------+-----------------+
| foo | 144 | 9 |
| bar | 9 | 264 |
+------+-------------------+-----------------+
retailer_view
+------+-------------------+-----------------+
| name | as_supplier_total | as_client_total |
+------+-------------------+-----------------+
| baz | 16 | 125 |
| qux | 245 | 16 |
+------+-------------------+-----------------+
我的两个困难是:
每个交易的supplier_id
和client_id
存储在两个多态关联中supplier_type
和{ {1}}可以是client_type
或App\Producer
。
每个交易的App\Retailer
和unit_price
都存储在子表中。
两个父表是:
quantity
在交易中,生产商和零售商可以是供应商或客户强>
Producer
+----+------+
| id | name |
+----+------+
| 1 | foo |
| 2 | bar |
+----+------+
Retailer
+----+------+
| id | name |
+----+------+
| 1 | baz |
| 2 | qux |
+----+------+
每个交易的详细信息记录在项表中:
Transaction
+----+---------+-------------+---------------+-----------+--------------+
| id | product | supplier_id | supplier_type | client_id | client_type |
+----+---------+-------------+---------------+-----------+--------------+
| 1 | a | 1 | App\Producer | 1 | App\Retailer |
| 2 | b | 2 | App\Retailer | 1 | App\Retailer |
| 3 | c | 1 | App\Producer | 2 | App\Producer |
| 4 | d | 2 | App\Retailer | 2 | App\Producer |
+----+---------+-------------+---------------+-----------+--------------+
来自下面验证答案的SQLFiddle:
答案 0 :(得分:1)
尝试以下查询:
对于制作人:
SELECT
p.name,
SUM(i.quantity * i.unit_price) AS as_supplier_total,
cagg.as_client_total
FROM producer p
LEFT JOIN transaction t on t.supplier_id = p.id AND t.supplier_type = 'App\\Producer'
LEFT JOIN item i ON t.id = i.transaction_id
LEFT JOIN (
SELECT
p.id,
SUM(i.quantity * i.unit_price) AS as_client_total
FROM producer p
LEFT JOIN transaction t on t.client_id = p.id AND t.client_type = 'App\\Producer'
LEFT JOIN item i ON t.id = i.transaction_id
GROUP BY p.id
) AS cagg ON cagg.id = p.id
GROUP BY p.id
对于零售商:
SELECT
r.name,
SUM(i.quantity * i.unit_price) AS as_supplier_total,
cagg.as_client_total
FROM retailer r
LEFT JOIN transaction t on t.supplier_id = r.id AND t.supplier_type = 'App\\Retailer'
LEFT JOIN item i ON t.id = i.transaction_id
LEFT JOIN (
SELECT
r.id,
SUM(i.quantity * i.unit_price) AS as_client_total
FROM retailer r
LEFT JOIN transaction t on t.client_id = r.id AND t.client_type = 'App\\Retailer'
LEFT JOIN item i ON t.id = i.transaction_id
GROUP BY r.id
) AS cagg ON cagg.id = r.id
GROUP BY r.id