Search code examples
sqlnode-mysql

Select row for every key in IN statement even if they are equal


Example for my question is follow:
I've got an array of id's

[ 6230, 206, 4259, 24761, 26736, 219, 281, 281, 516, 495, 10371 ]

And I want to setup SELECT query to my database.table like that:

SELECT * FROM `database`.`table` WHERE `id` IN (6230, 206, 4259, 24761, 26736, 219, 281, 281, 516, 495, 10371);

As you can see i've got 2 id that are equal so in result of that query i'll got only 10 rows.
But I want to get one row for every id in array. As I guesseing it is not posible with "IN()" statement.
Can I get any assumption's on how to solve this proplem.
Just to notice: I can't perform different query for every element of array.


Solution

  • Create a set with one record for each id, and join on that:

    select t.* from database.table as t inner join (
      select 6230 as id union all
      select 206 union all
      select 4259 union all
      select 24761 union all
      select 26736 union all
      select 219 union all
      select 281 union all
      select 281 union all
      select 516 union all
      select 495 union all
      select 10371
    ) as x on x.id = t.id