如何合并两个检查相同标志列但不同值的查询

kq0g1dla  于 2021-06-25  发布在  Mysql
关注(0)|答案(4)|浏览(361)

我有两个查询,用于根据标志值获取值之和

SELECT SUM(stock_deliveries.stockValue) AS stockValues1
FROM `stock_deliveries`
LEFT JOIN `delivery` ON `delivery`.`pk_deliveryId`  = `stock_deliveries`.`fk_deliveryId`
WHERE `stock_deliveries`.`fk_stockID` = '189'
AND `delivery`.`delivery_completed` = '1'

SELECT SUM(stock_deliveries.stockValue) AS stockValues2
FROM `stock_deliveries`
LEFT JOIN `delivery` ON `delivery`.`pk_deliveryId`  = `stock_deliveries`.`fk_deliveryId`
WHERE `stock_deliveries`.`fk_stockID` = '189'
AND `delivery`.`delivery_completed` = '0

是否可以在单个查询中合并此2查询?提前谢谢。

taor4pac

taor4pac1#

您可以在sum中使用“if”来检查是否需要中的值 stockValues1 或者 stockValues0 ```
SELECT SUM(IF(d.delivery_completed = 1, sd.stockValue, 0)) AS stockValues1, SUM(IF(d.delivery_completed = 0, sd.stockValue, 0)) AS stockValues2
FROM stock_deliveries sd
LEFT JOIN delivery d ON d.pk_deliveryId = sd.fk_deliveryId
WHERE sd.fk_stockID = '189'
AND (d.delivery_completed = 1 OR d.delivery_completed = 0)

显然,如果“delivery\u completed”仅为1或0,则可以忽略最后一个 `AND` 在查询中;)
编辑:正如thorstenkettner所回答的,在语法上也可以使用case,只有一个“case”它们基本上是等价的。这个 `if` 本例中的语法更简洁,但如果有更多选项,则更灵活,例如:

SELECT CASE sometable
WHEN 'top' THEN 'high'
WHEN 'center' THEN 'medium'
ELSE 'low'
END AS position

t3psigkw

t3psigkw2#

是的,您将使用条件聚合(即。 CASE WHEN 在聚合函数中,例如 SUM ):

select
  sum(case when d.delivery_completed = 0 then sd.stockvalue end) as stockvalues0,
  sum(case when d.delivery_completed = 1 then sd.stockvalue end) as stockvalues1
from stock_deliveries sd
left join delivery d on d.pk_deliveryid = sd.fk_deliveryid
where sd.fk_stockid = 189;
jyztefdp

jyztefdp3#

您可以在groupby的帮助下使用单个查询

SELECT SUM(stock_deliveries.stockValue) AS stockValues, `delivery`.`delivery_completed` as deliveryCompleted
FROM `stock_deliveries`
LEFT JOIN `delivery` ON `delivery`.`pk_deliveryId` =  `stock_deliveries`.`fk_deliveryId`
WHERE `stock_deliveries`.`fk_stockID` = '189'
GROUP BY `delivery`.`delivery_completed`;

这样,您将为的每个值都有一行 delivery_completed 使用关联的sum(如果只需要0和1的值,可以添加到where子句中) and delivery.delivery_completed IN (0,1) ). 例子:

stockValues    deliveryCompleted
       1000           0
        700           1
hsgswve4

hsgswve44#

你可以用 UNION ALL 运算符来保持两个结果行的逻辑,但它们现在位于相同的结果中,而不是两个分开的结果行

相关问题