gpt4 book ai didi

mysql - 同义词、外连接、单行字符串函数

转载 作者:行者123 更新时间:2023-11-29 22:11:33 28 4
gpt4 key购买 nike

如何返回订单详细信息表中每个订单的订单 ID 和数量总和。将总值标记为“总数量”,并仅返回总数量 > 250 的订单,并按总数量从最高到最低排序此订单?

最佳答案

这是针对 mysql 的。假设您指的是 sum(qty)

架构/加载数据测试

create table orders
( id int auto_increment primary key,
custId int not null
-- etc etc
-- fk to customer id
);

create table orderDetails
(
id int auto_increment primary key,
orderId int not null,
itemId int not null,
qty int not null,
-- etc etc
-- fk to items table not shown in the example

-- fk constraint to orders table below:
CONSTRAINT fk_orddet_ords FOREIGN KEY (orderId) REFERENCES orders(id)
);

insert orders (custId) values (1),(2),(3);
insert orderDetails (orderId,itemId,qty) values (1,1,9),(2,1,190),(2,1,100),(3,1,255);

-- the below shows that the fk constraint fails for faulty data (orderId 4 does not exist)
insert orderDetails (orderId,itemId,qty) values (4,1,9);

查询

如果您不执行inr,则 id 2 将不会显示(也就是说,如果您仅执行 qty>250 的连接)。并不是说没有更聪明的头脑,但这是我的:

select id,custId,qty from 
(select o.id,o.custId,sum(d.qty) as qty
from orders o
join orderDetails d
on d.orderId=o.id
group by o.id,o.custId) inr
where inr.qty>250
order by qty desc

+----+--------+------+
| id | custId | qty |
+----+--------+------+
| 2 | 2 | 290 |
| 3 | 3 | 255 |
+----+--------+------+
2 rows in set (0.05 sec)

关于mysql - 同义词、外连接、单行字符串函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31594023/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com