简体   繁体   English

MYSQL Select 其中字符串包含关键字

[英]MYSQL Select where string contains keywords

So, I've been doing some digging but I can't really find something specific.所以,我一直在做一些挖掘,但我真的找不到具体的东西。 Let's say I have a table called products with 2 columns: product_name and vendor .假设我有一个名为products的表,它有 2 列: product_namevendor

product_name  |  vendor
Item A        | Computer Mania
Item B        | Incredible Connection
Item C        | Computer Mania

So, now let's say hypothetically I don't remember how to spell computer and I say, okay I remember the name starts with co and ends with er and there is mania afterwards.所以,现在假设我不记得如何拼写computer ,我说,好吧,我记得名字以co开头,以er结尾,然后是mania

How can I build a SELECT query with those conditions in my WHERE?如何在 WHERE 中使用这些条件构建 SELECT 查询? I have no idea how to do it.我不知道该怎么做。

Here's what I tried: SELECT * FROM products WHERE vendor_name LIKE '%co%';这是我尝试过的: SELECT * FROM products WHERE vendor_name LIKE '%co%';

However this returns Incredible Connection as well, which I don't want.但是,这也会返回Incredible Connection ,这是我不想要的。

I would use REGEXP here:我会在这里使用REGEXP

SELECT *
FROM yourTable
WNERE vendor REGEXP '^co[a-z]*er mania';

This regex pattern says to find all vendors whose names have a first word starting with co and ending in er , followed by the word mania .此正则表达式模式表示要查找名称的第一个单词以co开头并以er结尾的所有供应商,然后是单词mania

You have to use SQL Wildcards properly.您必须正确使用 SQL 通配符。

The % wildcard represents zero or more characters. %通配符表示零个或多个字符。 So, if you use %co% , it will search the string co in the vendor column.因此,如果您使用%co% ,它将在供应商列中搜索字符串co vendor column in given example in the question has the string co in every row.问题中给定示例中的vendor列在每一行中都有字符串co

If you say that it starts with co and ends with er mania , then use the wildcards as vendor like 'co%er mania' .如果您说它以co开头并以er mania结尾,则使用通配符作为vendor like 'co%er mania' This will search the vendor column for the values which starts with co and ends with er mania这将在vendor列中搜索以co开头并以er mania结尾的值

select * from products where vendor like 'co%er mania';

Refer this to read more about SQL Wildcards.请参阅此处以了解有关 SQL 通配符的更多信息。

For your example, you would use like :对于您的示例,您将使用like

where vendor_name like 'co%er mania'

You may want to make this case independent as well, although that is the default in MySQL.您可能还希望使这种情况独立,尽管这是 MySQL 中的默认设置。

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

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