我的查询是根据炒菜表(3份)总结费用,结果应该是13000但我得到39000。
# Order table
-------------------------------------------
| Id | order | Name | Fee |
-------------------------------------------
| 1 | SELECT STATEMENT | ab | 13000 |
-------------------------------------------
# Work table
-----------------------------
| Id | user id | order id |
-----------------------------
| 1 | 123 | 1 |
| 2 | 123 | 1 |
| 3 | 123 | 1 |
-----------------------------
# Query
SELECT o.order_id, SUM(o.fee) AS total_words
FROM users AS u
LEFT JOIN works AS wr ON wr.user_id = u.id
LEFT JOIN orders AS o ON o.order_id = wr.order_id
WHERE u.id = 123
# Output =>
Array
(
[order_id] => 1
[fee] => 39000
)
我尝试了DISTINCT和分组,但得到了相同的结果。
答案 0 :(得分:1)
<强> SQL Fiddle Demo 强>
SELECT `user_id`, SUM(orders.`Fee`)
FROM (SELECT DISTINCT `user_id`, `order_id`
FROM works
) as user_work
JOIN orders
ON user_work.`order_id` = orders.`Id`
WHERE user_work.user_id = 123
<强>输出强>
| user_id | SUM(orders.`Fee`) |
|---------|-------------------|
| 123 | 13000 |