SQL 以表达式开头(使用“LIKE”)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5145537/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:29:01  来源:igfitidea点击:

SQL startswith (using `LIKE`) on an expression

sql

提问by HoverHell

What's an appropriate way to do startswith(expression)in SQL?

startswith(expression)在 SQL 中做什么的合适方法是什么?

I can do it with LIKE ((expression) || '%'), but it doesn't look very nice to me.

我可以用 来做LIKE ((expression) || '%'),但对我来说它看起来不太好。

Full query is in form:

完整的查询格式为:

SELECT …, (SELECT COUNT(*) 
           FROM post AS child 
           WHERE child.path LIKE (post.path || '%') 
          AND child.depth >= post.depth)
FROM post WHERE …

I suppose it is preferable to use LIKEbecause of DB indexing for this case.

我想最好使用LIKE这种情况下的数据库索引。

回答by Scott Anderson

Just use LIKE 'input%'. I.E:

只需使用LIKE 'input%'. IE:

WHERE child.path LIKE post.path + '%'

(I assume this is for SQL Server, though this syntax probably works elsewhere)

(我假设这是针对 SQL Server 的,尽管此语法可能适用于其他地方)

回答by Tom Anderson

In standard SQL, you can also say:

在标准 SQL 中,您还可以说:

where position(post.path in child.path) = 0

I don't know if your RDBMS supports that. PostgreSQL does.

我不知道你的 RDBMS 是否支持。PostgreSQL 可以。

回答by Antonio García

You can use

您可以使用

where DATE LIKE '[(SELECT STR(YEAR(GETDATE())-1))]%'

where DATE LIKE '[(SELECT STR(YEAR(GETDATE())-1))]%'

WHERE child.path LIKE '[(SELECT STR(YEAR(GETDATE())-1))]%' (post.path || '%')

WHERE child.path LIKE '[(SELECT STR(YEAR(GETDATE())-1))]%' (post.path || '%')