gpt4 book ai didi

php - 如何使用具有重复数据的数组查询 Sum?

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:22 26 4
gpt4 key购买 nike

我目前有一个带有产品编号的 PHP 数组。让我们称之为产品。在我的数据库中,我有一个表,其中包含产品编号和属于该产品的价格的组合。

问题:如果例如文章 #1 被订购两次,我的数组可以包含重复的条目。

如果我使用类似

的查询
SELECT SUM(price) FROM articles WHERE article_number IN (products)

1 的重复条目被丢弃。我要查找的查询给出了 10 + 10 + 12.5 + 9.95 的总和。

有没有办法在 MySQL 中执行此操作?

作为对我的数据的澄清:

products = [1, 1, 2, 3];

articles| article_number | price
__________________________________
| 1 | 10.0
| 2 | 12.5
| 3 | 9.95

谢谢你:)

最佳答案

winmutt 有一个可靠的答案。但是,如果您没有这样的表可以加入,那么您可以像这样构建查询:

select sum (p) from (
(select price as p from articles where article_number = 1)
union all
(select price as p from articles where article_number = 1)
union all
(select price as p from articles where article_number = 2)
union all
(select price as p from articles where article_number = 3)
) s

关于php - 如何使用具有重复数据的数组查询 Sum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30874656/

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