將GROUP BY pt.pt_productid
添加到您的選擇聲明中,以便將sum()
應用於產品組。
還考慮使用JOIN
而不是嵌套選擇。
使用更新
select pt_product_name,
(select sum(sal_qty) from sales_tb as sal
where pt.pt_productid=sal.sal_pt_productid
and sal.sal_updated_time>curdate()
) as salQty
from product_tb as pt
group by pt.pt_productid;
JOIN
:
select pt_product_name, sum(sal_qty) as salQty
from product_tb as pt
left outer join sales_tb sal on (pt.pt_productid = sal.sal_pt_productid
and sal.sal_updated_time>curdate())
group by pt.pt_productid
下面是一個樣本表結構充滿樣本值,並演示了查詢工作的優良:
DROP TABLE IF EXISTS `temp_db`.`product_tb`;
CREATE TABLE `temp_db`.`product_tb` (
pt_productid int(10) not null auto_increment,
pt_product_name varchar(20) not null,
primary key (`pt_productid`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `temp_db`.`sales_tb`;
CREATE TABLE `temp_db`.`sales_tb` (
sal_saleid int(10) not null auto_increment,
sal_pt_productid int(10) not null references product_tb.pt_productid,
sal_qty int(10) default 0,
sal_updated_time timestamp not null default current_timestamp,
primary key (`sal_saleid`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
添加樣本數據的表:
insert into product_tb(pt_product_name) values
('prod1'), ('prod2'), ('prod3'), ('prod4');
insert into sales_tb(sal_pt_productid, sal_qty) values
(1, 40), (1, 40), (1, 10), (1, 20),
(2, 4), (2, 4), (2, 4), (2, 4),
(3, 1), (3, 1), (3, 1),
(4, 5), (4, 5);
選擇語句的結果(都返回相同的結果集):
# pt_product_name, salQty
prod1 110
prod2 16
prod3 3
prod4 10
注意,一個量將只相加,如果它今天或晚些時候賣出*! sal_update_time > curdate();
如果產品沒有curdate()或更高版本的任何銷售,它甚至不會出現在列表中。這並不意味着選擇錯誤,這意味着你沒有正確指定你的目標是什麼。
請使用代碼格式化,並嘗試生成具有預期輸出的數據樣本。 –