S
S
Stanislav Romanov2015-05-29 08:34:22
MySQL
Stanislav Romanov, 2015-05-29 08:34:22

SQL query with id selection from list?

Hello.
MySQL database.
There is a table like:

CREATE TABLE `test` (
  `id` INT(11) NULL DEFAULT NULL,
  `value` INT(11) NULL DEFAULT NULL
)

id        |         value
------------------------------------
   1                     10
   2                     15
   3                     23

I need to get the sum of value, id from the list, for example - "1, 1, 2".
The problem is that there are duplications of id. And just adding a WHERE IN condition won't work.
In theory, you can create a temporary table in memory, attach and sum the necessary fields, but maybe someone has a faster and more correct solution?
Update:
This request is NOT correct:
SELECT SUM(value) FROM test WHERE id IN (1, 1, 2);
Update 2:
The id list is external data, taking into account which you need to get the sum of the value fields.
If we take the list id: 1, 1, 2
Then the query should return 35 (10 + 10 + 15)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Evgeniy Zavyalov, 2015-05-29
@Kaer_Morchen

as an option ... collect 1,1,2 in
and join

select sum(value) 
  from test t
     , (select 1 id union all select 1 id union all select 2 id) tab
 where t.id = tab.id

D
Dmitry Entelis, 2015-05-29
@DmitriyEntelis

Taking into account Update 2 - imho the most correct decision is to select value from base where in and to summarize in .

B
barcik, 2015-05-29
@flashg

SELECT id, SUM(value) FROM test GROUP BY id

A
Alexey, 2015-05-29
@HaJIuBauKa

It's on the forehead so to speak

select sum(val1) from (SELECT (select value from test t2 where t2.id=t1.id) val1 FROM test t1 WHERE id IN (1, 1, 2));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question