Select query using IN() and without any sorting

隐身守侯 提交于 2019-11-30 13:09:56

问题


My query

select * from product where productId in(25,36,40,1,50);

Result shows as follows

`productId   ProductName  Qty Price`
-------------------------------------
`1          | namesome  | 5 | 25.00`
`25         | namesome  | 5 | 35.00`
`36         | namesome  | 5 | 35.00`
`40         | namesome  | 5 | 35.00`
`50         | namesome  | 5 | 35.00`

I did not use any order by clause, But its automatically applied order by productId,
I need result with out any sort, as follows

`productId   ProductName  Qty Price`
-------------------------------------
`25        | namesome  | 5 | 25.00`
`36        | namesome  | 5 | 35.00`
`40        | namesome  | 5 | 35.00`
`1         | namesome  | 5 | 35.00`
`50        | namesome  | 5 | 35.00`

How can I achieve this?
Database Engine: MyIsam, Collation: utf8_general_ci, PrimaryKey on productId


回答1:


select * 
from product 
where productId in(25,36,40,1,50) 
order by find_in_set(productId, '25,36,40,1,50');

See this SQLFiddle




回答2:


If you want them to be randomly ordered, do:

select * from product where productId in(25,36,40,1,50) ORDER BY RAND()

The default ordering is probably due to the way the IDs are sorted in the index.



来源:https://stackoverflow.com/questions/13657859/select-query-using-in-and-without-any-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!