输入参数上带有通配符的 SQL 选择查询

发布于 2024-10-27 14:14:18 字数 711 浏览 2 评论 0原文

基本上与我的其他线程同样的问题!

我有一个数据库表,我需要编写一个查询,该查询将根据字符串的部分匹配返回结果。

Example: 

DB field: abc 

Search term: 123abc

i.e. I want given 123abc for it to return the row that has the abc field in it!

My attempt:

SELECT mood from users where '$searchTerm' like '%' || dbField

类似的事情有可能发生吗?


好吧,基本上我正在尝试将数字与搜索词 la77740985

id   | mood  | numberfield
====   =====   ============
1      bad      '77740985'
2      good     '77513755'

运行查询返回两行!

注意:通配符只能出现在字符串的开头,换句话说,我希望搜索词以任何内容开头,但仍然与数据库中基本上具有相同结尾的字符串匹配。

Same question as my other thread basically!

I have a db table and I need to write a query that will return results based on a partial match of a string.

Example: 

DB field: abc 

Search term: 123abc

i.e. I want given 123abc for it to return the row that has the abc field in it!

My attempt:

SELECT mood from users where '$searchTerm' like '%' || dbField

Is something like that possible in any way?


Well basically I'm trying to match the numbers with the search term la77740985

id   | mood  | numberfield
====   =====   ============
1      bad      '77740985'
2      good     '77513755'

Running the query returns both rows!

Note: The wildcard should only be in the beginning of the string in other words I want the search term to begin with anything but still match the string from the database that basically have the same ending.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

高冷爸爸 2024-11-03 14:14:18

它的工作原理如下:

从用户中选择心情,其中 '$searchTerm' 像 concat('%',numberField);

It worked like this:

SELECT mood from users where '$searchTerm' like concat('%',numberField);

神经大条 2024-11-03 14:14:18
SELECT mood
from users
where '$searchTerm' like '%' || numberField

这会将 $searchTerm = '123abc' 与包含 'abc' 的 dbField 进行匹配。这是正确的。如果您需要包含(任何地方),请添加 || '%' 位于末尾。

完整的测试脚本

drop table if exists users2;
create table users2 (mood, numberfield);
insert into users2(mood,numberfield) values ('happy','77740985');
insert into users2(mood,numberfield) values ('sad','77513755');

然后运行此

SELECT mood from users2 where 'la77740985' like ('%' || numberfield);

输出

mood
=======
'happy'
SELECT mood
from users
where '$searchTerm' like '%' || numberField

This will match $searchTerm = '123abc' against dbField that contains 'abc'. It's correct. If you need contains (anywhere), then add || '%' at the end.

Full test script

drop table if exists users2;
create table users2 (mood, numberfield);
insert into users2(mood,numberfield) values ('happy','77740985');
insert into users2(mood,numberfield) values ('sad','77513755');

Then run this

SELECT mood from users2 where 'la77740985' like ('%' || numberfield);

Output

mood
=======
'happy'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文