Is there a way to include duplicates from a MySQL query: select..from..where..id in (list)

I am trying to get results for a query type

SELECT * FROM table WHERE id IN(2,4,6,1,1,2) ORDER BY field (id,2,4,6,1,1,2)

and I want to get the results in the same order as the list, including: duplicates. The above query keeps order, but cuts out duplicates. I know I can post the results, but just wondering if there is an easier way.

thank

+5
source share
2 answers

This will allow you to achieve what you want:

SELECT * FROM table
inner join (
   select 1 as sort, 2 as value union all
   select 2, 4 union all
   select 3, 6 union all
   select 4, 1 union all
   select 5, 1 union all
   select 6, 2) X on X.value=table.id
ORDER BY X.sort
+3
source

How do you build a query? If you do not mind a bit of manual work (which could later be wrapped with some code), the unions should get what you need:

select id from table where id in (1, 2, 4, 6)
union all
select id from table where id in (6, 8);

Return:

------
| id |
|====|
| 1  |
| 2  |
| 4  |
| 6  |
| 6  |
| 8  |
------

: , , . .

0

All Articles