Mysql 如何从特定ID获取按desc排序的行

Mysql 如何从特定ID获取按desc排序的行,mysql,sql-order-by,Mysql,Sql Order By,我的目标是:获得大多数已确认发货地点的订购请求 采购请求链接到装运位置(仓库) 我有一张桌子: CREATE TABLE IF NOT EXISTS `shipment_locations` ( `id` int(6) primary key, `name` varchar(200) NOT NULL ); INSERT INTO `shipment_locations` (`id`, `name`) VALUES ('1', 'france'), ('2', 'usa'),

我的目标是:获得大多数已确认发货地点的订购请求

采购请求链接到装运位置(仓库)

我有一张桌子:

CREATE TABLE IF NOT EXISTS `shipment_locations` (
  `id` int(6) primary key,
  `name` varchar(200) NOT NULL
);
INSERT INTO `shipment_locations` (`id`, `name`) VALUES
  ('1', 'france'),
  ('2', 'usa'),
  ('3', 'spain'),
  ('4', 'germany');
  
CREATE TABLE IF NOT EXISTS `purchase_requests` (
  `id` int(6) primary key,
  `name` varchar(200) NOT NULL,
  `total_cost_confirmed` int(6) NULL,
  `shipment_location_id` int(6) NULL,
 FOREIGN KEY (`shipment_location_id`) REFERENCES `shipment_locations` (`id`)
);

INSERT INTO `purchase_requests` (`id`, `name`, `total_cost_confirmed`, `shipment_location_id`) VALUES
  ('1', 'pr1', '109', 1),
  ('2', 'pr2', '1500', 3),
  ('3', 'pr3', '3000', 2),
  ('4', 'pr4', '10000', 2),
  ('5', 'pr5', '5', 3),
  ('6', 'pr6', '3000', 2),
  ('7', 'pr7', '3000', 2),
  ('8', 'pr8', '1', 3),
  ('9', 'pr9', '10000000', 3);
对于按发货地点订购且确认成本最高的产品,这非常简单:

SELECT shipment_location_id, SUM(total_cost_confirmed) totalConfirmed
FROM purchase_requests
GROUP BY shipment_location_id
ORDER BY totalConfirmed DESC
它在这里非常有效:

但是,然后我尝试按采购请求id进行筛选(添加
按id分组
在(…)中的id位置
),它给了我错误的顺序(因为它取的是结果中存在的id)。
=>()

在按采购申请id进行筛选时,如何从第一次查询中保留正确的订单

添加sqlfiddle:


提前感谢您的帮助:)

首先聚合以获得已确认的
总数的总和,然后加入表:

SELECT p.id, p.name, p.shipment_location_id, t.totalConfirmed
FROM purchase_requests p 
INNER JOIN (
  SELECT shipment_location_id, SUM(total_cost_confirmed) totalConfirmed 
  FROM purchase_requests
  GROUP BY shipment_location_id
) t ON t.shipment_location_id = p.shipment_location_id
WHERE p.id IN ('1', '3', '4', '8')
ORDER BY t.totalConfirmed DESC
请参阅。
结果:


不可能保持每一个装运地点的总确认和检索正确的购买请求ID和名称?您认为哪个ID和名称对于每个代码都是正确的?<每一个代码> StuttMySturoSIDID <代码> s 1, 2和3?这里是我需要的结果:(参见最后的评论在小提琴)谢谢@ Frpas,它工作完美!
> id | name | shipment_location_id | totalConfirmed
> -: | :--- | -------------------: | -------------:
>  4 | pr4  |                    2 |          19000
>  3 | pr3  |                    2 |          19000
>  8 | pr8  |                    1 |            110
>  1 | pr1  |                    1 |            110