如何通过包含重复ID的ID列表获取行?

时间:2019-12-24 06:30:17

标签: mysql sql

我有一个id的列表

1,1,2,3,3,3,1

,并希望计算以上各行的总和。如果我将IN用作

SELECT SUM(score) FROM table1 WHERE id IN(1,1,2,3,3,3,1)

这将是三行(唯一ID)的总和,但我也需要包括重复的行(1,1,2,3,3,3,1的7行)。

编辑:表结构很简单。像

CREATE TABLE table1
(
id int(11) unsigned NOT NULL AUTO_INCREMENT,
score int(11),
PRIMARY KEY (id)
) ENGINE=InnoDB

2 个答案:

答案 0 :(得分:2)

您需要创建一个包含这些id值的派生表,然后将JOIN到您的table1来为列表中每个值实例生成行。然后可以对这些行求和:

SELECT SUM(score)
FROM (SELECT 1 AS id UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
                     UNION ALL SELECT 3 UNION ALL SELECT 3 UNION ALL SELECT 1) ids
JOIN table1 t1 ON t1.id = ids.id

Demo on dbfiddle

答案 1 :(得分:0)

您不能使用IN条件执行此操作,因为IN将您的商品视为一个集合(即,确保唯一性)。

您可以通过加入UNION ALL来产生所需的结果,如下所示:

  

1,1,2,3,3,3,1

SELECT SUM(Score)
FROM Table_1 t
JOIN ( SELECT 1 AS ID
       UNION ALL SELECT 1 AS ID
       UNION ALL SELECT 2 AS ID
       UNION ALL SELECT 3 AS ID
       UNION ALL SELECT 3 AS ID
       UNION ALL SELECT 3 AS ID
       UNION ALL SELECT 1 AS ID
 ) x ON x.ID = t.ID

CREATE TABLE #TempIDs
(
   ID int
)
INSERT INTO #TempIDs (1)
INSERT INTO #TempIDs (1)
INSERT INTO #TempIDs (2)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (1)

Select SUM(Score) From Table_1
INNER JOIN #TempIDs t n Table_1.ID = t.ID;