简体   繁体   English

SQL SELECT,其中单元格为一定长度并包含特定字符

[英]SQL SELECT where cell is a certain length and includes specific characters

I'm trying to create a SELECT statement that selects rows where NAME is max. 我正在尝试创建一个SELECT语句,该语句选择NAME最大的行。 5 characters and the . 5个字符和。 is in the NAME. 在NAME中。 I only want the first, so I'm including a LIMIT 1 to the statement. 我只想要第一个,所以我在语句中添加了LIMIT 1。

I have worked with the following 我曾与以下工作

searchstring = "."
sql = "SELECT * FROM Table WHERE NAME LIKE %s LIMIT 1"
val = (("%"+searchstring+"%"),)
cursor.execute(sql, val)

But I'm not sure how to incorporate the length of NAME in my statement. 但是我不确定如何在我的陈述中加入NAME的长度。

My "Table" is as follows: 我的“表格”如下:

ID     NAME
1      Jim
2      J.
3      Jonathan
4      Jack M.
5      M.S.

So based on the table above, I would expect row 2 and 5 to be selected. 因此,根据上表,我希望选择第2行和第5行。 I could select all, and loop through them. 我可以选择全部,然后遍历它们。 But as I only want the first, I'm thinking I would prefer a SQL statement? 但是,由于我只想要第一个,所以我想使用SQL语句?

Thanks in advance. 提前致谢。

您可以将CHAR_LENGTH函数与LIKE一起使用:

SELECT * FROM Table WHERE name LIKE '%.%' AND CHAR_LENGTH(name) <= 5 LIMIT 1

Try LEN() Select LEN( result string ); 尝试LEN()选择LEN( 结果字符串 ); This will return the length of string. 这将返回字符串的长度。 but this will count spaces also. 但这也会计算空格。 Try removing it with LTRIM(). 尝试使用LTRIM()删除它。

Oracle SQL Oracle SQL

SELECT * FROM Table WHERE name LIKE '%.%' AND LENGTH(name) < 6 and rownum < 2

Base on the sql language(oracle, mysql, sql server, etc) use 基于sql语言(oracle,mysql,sql server等)使用

length() or char_length() length()或char_length()

rownum or limit 行数或限制

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

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