postgresql 如何将整数转换为字符串并获取字符串的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22476601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert integer to string and get length of string
提问by coala
In my database there is a field last_id
of type integer
. The table contains several rows. Let's say the maximum value of last_id
is 104050. Now I want to know the lengthof this integer.
在我的数据库中有一个last_id
类型的字段integer
。该表包含几行。假设 的最大值last_id
是 104050。现在我想知道这个整数的长度。
As this is not possible I am trying to convert it into a string.
由于这是不可能的,我正在尝试将其转换为字符串。
SELECT to_char(MAX(last_id),'99') FROM xxxx
I would expect this to yield 10 with type = text, but instead it returns ## type = text.
Afterwards I would use SELECT char_length(to_char(MAX(last_id),'99')) FROM xxx
which should return 2 ...
我希望这会在 type = text 的情况下产生 10,但它会返回 ## type = text。之后我会使用SELECT char_length(to_char(MAX(last_id),'99')) FROM xxx
which 应该返回 2 ...
What is going wrong here?
这里出了什么问题?
回答by Erwin Brandstetter
回答by Stoddard
Since you are dealing with integers you can actually find the length of the number (or number of digits in the number) directly. Mathematically, the number of digits in an integer is one more than the floor of the log base 10 of the number.
由于您正在处理整数,您实际上可以直接找到数字的长度(或数字中的位数)。在数学上,整数中的位数比该数以 10 为底的对数的下限多 1。
You could use the following to find the length directly:
您可以使用以下内容直接查找长度:
SELECT FLOOR(LOG(MAX(last_id))) + 1 FROM xxxx
回答by rjhdby
Don't work with postgresql, but after documentation read... Somthign like this.
不要使用 postgresql,但在阅读文档后......像这样的 Somthign。
SELECT character_length(cast(last_id as varchar(20))) from table
从表中选择 character_length(cast(last_id as varchar(20)))