我有一个类似于的表
-----------+------|
product_id |price |
-----------+------|
1 + 5 |
-----------+------|
2 + 15 |
-----------+------|
3 + 25 |
-----------+------|
我需要这样的输出:
-----------+------|
product_id |sum |
-----------+------|
1 + 45 |
-----------+------|
2 + 45 |
-----------+------|
3 + 45 |
-----------+------|
我当前的查询:
SELECT product_id, (SELECT SUM(price) FROM tableName) `sum` FROM tableName.
是否可以在不使用2个SELECT查询或GROUP_CONCT的情况下执行此操作?请帮忙。
提前感谢!
注意:我的表中有数千行,更多的条件(包括其他表数据)将被添加到这个查询中。
只需使用group-by.
SELECT
product_id, (SELECT SUM(price) FROM tableName) `sum`
FROM
tableName
group by .
使用这样的查询:
SELECT *, sum(price) AS sum FROM table WHERE condition = value
SELECT product_id , sum(price) AS sum FROM table WHERE condition = value
尽量不要在select语句中使用子查询。
您可以尝试此代码
select product_id, (select sum(price) from PRODUCTS) as sum FROM products