简体   繁体   English

以升序获取表中的字母数字值

[英]Fetching alphanumeric values in a table in ascending order

I have a table Food which contains column Quantity(it contains values- 10 kg,32 kg,5 kg). 我有一个表Food,其中包含“数量”列(它包含的值是10公斤,32公斤,5公斤)。 I want to fetch Quantity values in acsending order . 我想按升序获取数量值。

Now I have query: 现在我有查询:

select Quantity from Food

output=> 输出=>

10 kg 10公斤

32 kg 32公斤

5 kg 5公斤

But expected result is : 但是预期结果是:

5 kg 5公斤

10 kg 10公斤

32 kg 32公斤

How can I sort this alphanumeric value in SQL? 如何在SQL中对该字母数字值排序?

Try: 尝试:

SELECT Quantity from Food ORDER BY CAST(Quantity as UNSIGNED) DESC;

This isn't ideal, you should store the quantity as an integer field and the unit as an enum. 这不是理想的选择,您应该将数量存储为整数字段,并将单位存储为枚举。

If the unit is only kg then you can try like below. 如果单位只有kg则可以尝试以下操作。 See a demo fiddle here http://sqlfiddle.com/#!9/e644f/6 在此处查看演示小提琴http://sqlfiddle.com/#!9/e644f/6

select Quantity from Food
order by replace(Quantity,'kg','') * 1;

Depending on the actual data you can grab the numeric part from the front of the value and than order by it: 根据实际数据,您可以从值的前面抓取数字部分,然后按顺序排序:

SELECT Quantity 
  FROM Food 
 ORDER BY CAST(LEFT(Quantity,INSTR(Quantity,' ')-1) AS DECIMAL) DESC;

However as @Martin indicates MySQL appear to do that much for you. 但是,如@Martin所示,MySQL似乎为您做了很多。 This is more explicit and there is, perhaps, value in that. 这更为明确,也许有价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM