mysql> select * from orders;
+---------+------------+------------+------------+----------+----------+
| orderid | customerid | orderdate | shipdate | shipping | salestax |
+---------+------------+------------+------------+----------+----------+
| 1 | 1 | 2008-03-31 | 2008-03-31 | 4.99 | 5.00 |
| 2 | 1 | 2008-04-01 | 2008-04-02 | 5.99 | 5.00 |
| 3 | 2 | 2008-04-01 | 2008-04-02 | 3.99 | 6.00 |
| 4 | 3 | 2008-04-02 | 2008-04-02 | 6.99 | 7.50 |
+---------+------------+------------+------------+----------+----------+
4 rows in set (0.02 sec)
mysql> select * from orderinfo;
+---------+------------+-----+-------+----------+
| orderid | isbn | qty | price | detailid |
+---------+------------+-----+-------+----------+
| 1 | 0929306279 | 1 | 29.95 | 1 |
| 1 | 0929306260 | 1 | 49.95 | 2 |
| 2 | 0439357624 | 3 | 16.95 | 3 |
| 3 | 0670031844 | 1 | 34.95 | 4 |
| 4 | 0929306279 | 1 | 29.95 | 5 |
| 4 | 0929306260 | 1 | 49.95 | 6 |
| 4 | 0439357624 | 1 | 16.95 | 7 |
| 4 | 0670031844 | 1 | 34.95 | 8 |
+---------+------------+-----+-------+----------+
8 rows in set (0.00 sec)
我试图将数量和价格从orderinfo表中相乘,然后在我尝试复制它们时从订单表中添加运费它工作正常但是当我添加运费时我得到的值不正确
这是有效的
mysql> select orders.orderid,sum(orderinfo.qty*orderinfo.price) as order_total from orders
-> inner join orderinfo
-> on orders.orderid=orderinfo.orderid
-> group by orderid;
+---------+-------------+
| orderid | order_total |
+---------+-------------+
| 1 | 79.90 |
| 2 | 50.85 |
| 3 | 34.95 |
| 4 | 131.80 |
+---------+-------------+
4 rows in set (0.00 sec)
这会给出不正确的值
mysql> select orders.orderid,sum(orderinfo.qty*orderinfo.price+orders.shipping) as order_total from orders
-> inner join orderinfo
-> on orders.orderid=orderinfo.orderid
-> group by orderid;
+---------+-------------+
| orderid | order_total |
+---------+-------------+
| 1 | 89.88 |
| 2 | 56.84 |
| 3 | 38.94 |
| 4 | 159.76 |
+---------+-------------+
4 rows in set (0.00 sec)
答案 0 :(得分:2)
您正在 你可以通过向shipping
聚合中应用SUM()
费率,之后需要将其添加到SUM()
的结果中。这样可以为聚合组的每个行添加shipping
值,即orderid = 1
的双重送货和orderid = 4
的4倍送货。< / p>
shipping
添加GROUP BY
来实现这一点(实际上MySQL并不需要这样做,但这是一个好习惯)。
SQLFiddle.com上的SELECT
orders.orderid,
/* Add `shipping` outside the SUM() aggregate */
SUM(orderinfo.qty*orderinfo.price) + orders.shipping AS order_total
FROM orders
INNER JOIN orderinfo ON orders.orderid = orderinfo.orderid
GROUP BY
orderid,
shipping
Here's an example。