MySQL查询以特定顺序返回结果,而无须按顺序 [英] MySQL query to return results in specific order without order by

查看:315
本文介绍了MySQL查询以特定顺序返回结果,而无须按顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使mysql查询返回没有默认顺序的值,例如我正在使用以下查询

select id_product,name from sample where id_product in ('675','123','745','954').

,但它按id_product给出输出行的顺序. 输出:

id_product,Name
123        ,abc
675        ,xzy
745        ,bsh
954        ,dsh

我希望结果应该像这样,没有默认顺序.

 id_product,Name
 675        ,xzy
123        ,abc    
745        ,bsh
954        ,dsh

任何帮助将不胜感激.

我建议在数据库中添加一个Sort列以强制执行自定义顺序.无论如何,您可以使用 FIND_IN_SET 功能:

SELECT id_product, name
FROM sample
WHERE id_product IN (675,123,745,954)
ORDER BY FIND_IN_SET(id_product, '675,123,745,954')

演示

Is it possible to make a mysql query returning values without default order.for example am using the below query

select id_product,name from sample where id_product in ('675','123','745','954').

but it giving the output rows order by id_product. OUTPUT:

id_product,Name
123        ,abc
675        ,xzy
745        ,bsh
954        ,dsh

I want the result should come like this, without default order.

 id_product,Name
 675        ,xzy
123        ,abc    
745        ,bsh
954        ,dsh

any help would be appreciated.

解决方案

I suggest adding a Sort column in the database to force a custom order. Anyway, you can use a little trick using the FIND_IN_SET function:

SELECT id_product, name
FROM sample
WHERE id_product IN (675,123,745,954)
ORDER BY FIND_IN_SET(id_product, '675,123,745,954')

Demo

这篇关于MySQL查询以特定顺序返回结果,而无须按顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆