获取作为IDS数组的重复项的总和

  • 本文关键字:获取 IDS 数组 mysql sql
  • 更新时间 :
  • 英文 :


我对通过IDS获取项目的总和有疑问。有什么优雅的方法可以用sql过程做到这一点吗?IDS来自阵列中,例如(10、10、11、11、12(。所以总数应该是300。如果我是对的,函数不能将数组作为mysql中的参数,所以它可以是过程。

我能想到的最接近的:

SELECT price FROM table WHERE FIND_IN_SET(ID, (10, 10, 11, 11, 12))

尽管它不能正常工作。我知道SUM几乎满足了我的需求,只是它跳过了重复的值,如果有一种方法可以使用它,它不会跳过,那么它可能是最快的。下表:

|---------------------|------------------|
|          ID         |       Price      |
|---------------------|------------------|
|          10         |         34       |
|---------------------|------------------|
|          11         |         99       |
|---------------------|------------------|
|          12         |         34       |
|---------------------|------------------|

您将创建一个派生表和join:

select sum(t.price)
from (select 10 as id union all
select 10 as id union all
select 11 as id union all
select 11 as id union all
select 12 as id 
) i join
t
on i.id = t.id;

在MySQL 8.0中,您可以通过JSON_TABLE运行输入数组来实现这一点,它将把数组条目解释为行。

这种方法尊重数组的顺序,不会跳过双工,因为它不像WHERE那样是一个过滤函数。

set @arr = '[10, 10, 11, 11, 12]';
select * 
from json_table(@arr, '$[*]' columns (id int path '$')) input
left join products using (id);
->  id  price
10  34
10  34
11  99
11  99
12  34
select sum(price) 
from json_table(@arr, '$[*]' columns (id int path '$')) input
left join products using (id);
->  300

最新更新