MySQL 是否有与 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找
LPAD
函数:编辑:
正如 @Brad 在评论中指出的,您还可以使用 ZEROFILL 定义列:
这将始终生成至少 3 位数字(它将用零填充)小于 3 位的数字,并且不会影响更多)。如果您总是需要像这样输出数字(而不仅仅是在一个查询中),那么它很有用......
You're looking for the
LPAD
function:Edit:
As pointed out by @Brad in the comments, you could also define the column with ZEROFILL:
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)...
如果您想实现最小数量的填充,而不剪切较大数字的结果,则需要使用
IF
语句。下面的示例将确保所有 ID 至少具有三位数,同时让较大的 ID 仍然不加修饰地通过。
If you want to achieve a minimum number of padding, without cutting the results of larger numbers, you'll need to use an
IF
statement.The example below will make sure all IDs have a minimum of three digits, while letting larger IDs still pass through untrimmed.
根据您拥有的 mySql 版本,您可以定义一个 UDF 来为您格式化该值。参见http://dev.mysql.com/doc/refman/ 5.1/en/adding-functions.html。
Depending on the version of mySql you have, you could define a UDF that would format the value for you. see http://dev.mysql.com/doc/refman/5.1/en/adding-functions.html.