开发者

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

I am trying to get the results for the 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 results in the same order as the list including : the duplicates. The above query retains the order but cuts out duplicates. I know I can post-process the results but just wondering if 开发者_Python百科there is an easier way.

Thanks


This will actually 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


How are you building the query? If you're not opposed to doing a little manual work (which you could later wrap in some code), unions should get you 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);

Returns:

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

EDIT: Actually, I don't think that helps your ordering, though. Let me play with this some more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜