开发者

Finding field with longest length in a column

开发者 https://www.devze.com 2023-01-08 19:39 出处:网络
How do I fi开发者_运维问答nd the field with the longest length of a specific column in a MySQL table?MySQL has a lot of string functions you can use:

How do I fi开发者_运维问答nd the field with the longest length of a specific column in a MySQL table?


MySQL has a lot of string functions you can use:

SELECT LENGTH(col) as my_len FROM my_table ORDER BY my_len DESC LIMIT 1

More funky version (it works):

SELECT MAX(LENGTH(col)) FROM my_table


You can use the mysql command LENGTH()

<?php 
$q = mysql_query("SELECT LENGTH(yourfield) AS fieldlength FROM yourtable ORDER BY fieldlength DESC LIMIT 1"); 
echo $longestfield = mysql_result($q,0); 
?>


Let the name of the table be tbl1 and the name of the column be col1 in which you are trying to find the longest length value.

Approach 1:

select col1, length(col1) from tbl1 order by length(col1) desc limit 1

This will return the value and also the length of the value.

The above approach is best if their is only a single row or you want to retrieve only one row which is having the longest length. In case their are multiple rows which have longest length and you want to retrieve them all then the second Approach would be the best.

Approach 2:

select col1, length(col1) from tbl1 where length(col1) in (select max(length(col1)) from tbl1)

This will return both the value and also the length of the value of all the rows which is having the longest value.


You may wanna consider CHAR_LENGTH(). Differences from documentation:

CHAR_LENGTH(): Return number of characters in argument

LENGTH(): Return the length of a string in bytes

For example, when using UTF-8 on your column, these functions return different values.

And note that the length you set for a string column (ex: varchar) is actually its character length.

0

精彩评论

暂无评论...
验证码 换一张
取 消