MySQL相当于sprintf吗? [英] Is there a MySQL equivalent of sprintf?
问题描述
我的表中有一个INT字段,我想选择该字段为零填充字符串.因此,例如,8表示为008
,23表示为023
,依此类推.在MySQL查询中有可能吗?
I have an INT field in my table, which I'd like to select as a zero-padded string. So for example, 8 would come out as 008
, 23 as 023
and so on. Is this possible in a MySQL query?
推荐答案
You're looking for the LPAD
function:
SELECT LPAD(23, 3, '0'); -- '023'
正如@Brad在评论中指出的那样,您还可以使用ZEROFILL定义该列:
As pointed out by @Brad in the comments, you could also define the column with ZEROFILL:
`foo` INT(3) ZEROFILL
这将始终产生至少3位数字(它将零位填充的数字少于3位,而不会影响更多数字).如果您总是需要这样的数字(而不只是在一个查询中),这很有用...
This would always produce at least 3 digit numbers (It would zero-pad numbers less than 3 digits, and not effect those more). It's useful if you always need the numbers to come out like that (And not just in one query)...
这篇关于MySQL相当于sprintf吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!