我很努力地得到這個查詢的權利。每次我改變它,它都會破壞別的東西。如何糾正這個SQL查詢? SUM加入
SELECT products.id,
products.name,
COUNT(transactions.id) AS sales,
IFNULL(SUM(cart.price_paid), 0) AS amount
FROM products
LEFT JOIN cart ON cart.product_id = products.id
LEFT JOIN transactions ON cart.transaction_id = transactions.id AND transactions.status = 'COMPLETED'
WHERE products.user_id = $id
AND products.active = 1
AND transactions.id IS NOT NULL
GROUP BY products.id
以上正在試圖獲得的用戶,具有的產品,如果不考慮他們的銷售還是沒有,然後顯示出它的銷售。
目前,因爲我有AND transactions.id IS NOT NULL
它不顯示所有產品。只有那些有銷售。如果我刪除這個,那麼我會看到所有的產品,但amount
字段將是不正確的,因爲金額將被誇大。
這些都是一些基本實例表:
# Products Table
+----+------+---------+--------+
| id | name | user_id | active |
+----+------+---------+--------+
| 1 | cup | 4 | 1 |
| 2 | ball | 4 | 1 |
+----+------+---------+--------+
# Cart Table
+----+------------+----------------+-------------+
| id | product_id | transaction_id | Price_paid |
+----+------------+----------------+-------------+
| 1 | 1 | 6 | 1.99 |
| 2 | 1 | 7 | 1.99 |
| 3 | 1 | 8 | 1.99 |
| 4 | 1 | 9 | 1.99 |
+----+------------+----------------+-------------+
# Transactions Table
+----+--------+-----------+
| ID | amount | status |
+----+--------+-----------+
| 6 | 1.99 | COMPLETED |
| 7 | 1.99 | COMPLETED |
| 8 | 2.99 | CREATED |
| 9 | 2.99 | CREATED |
+----+--------+-----------+
# Result
+----+------+-------+--------+
| id | name | sales | amount |
+----+------+-------+--------+
| 1 | Cup | 2 | 3.98 |
| 2 | Ball | 0 | 0 |
+----+------+-------+--------+
請顯示一些樣品數據和所期望的結果。 – Barmar
我已經添加了一個例子。 – Abs
「產品」表中的user_id列在哪裏?不應該把它叫做'Products'就像在你的查詢中一樣? – Barmar