mysql 详细查询字符串,如通配符
不知道如何标题我的问题...哈哈。
下面是我需要的。
我的数据库中的值如下所示: test_example-1、test_example-2、test_example-TD-1
这些值的长度可能有所不同,“test_example-”只是一个示例,某些值将具有不同的名称。
当我执行查询来获取所有看起来像“test_example-”的值时,我得到了所有内容,因为我以这种方式使用通配符值“test_example-%”。但是,我不希望结果中出现“test_example-TD-1”。我只想要非 TD 值。那么,我怎样才能获得所有“test_example-”而不得到“-”后不仅仅是一位数字整数的东西。
数据库中的值在“-”之后最多只能包含一个数字 (0-9)。所以基本上我需要一个查询来搜索类似于“test_example-[0-9]”的值。
我怎样才能做到这一点?如果这令人困惑并且需要澄清,请告诉我。谢谢!
这是我为缓解一些困惑而所做的确切查询:
SELECT MAC, NAME FROM HOST WHERE NAME LIKE (SELECT CONCAT(LEFT(NAME, LENGTH(NAME)-1), "%") FROM HOST WHERE MAC="some mac address");
这是工作结果(感谢 swati ):
SELECT MAC, NAME FROM HOST WHERE NAME REGEXP CONCAT(LEFT(NAME, LENGTH(NAME)-1), "[0-9]+") AND MAC="some mac address";
Not sure how to title my question... lol.
Below is what i am needing.
Values in my database look like the following: test_example-1, test_example-2, test_example-TD-1
The values can vary in length, "test_example-" is just an example, some of the values will have varying names.
When i perform a query to grab all the values that look like this "test_example-" i get everything, because i am using the wild card value this way "test_example-%". However, i do not want the "test_example-TD-1" in the result. I only want the NON-TD values. So, how can i get all the "test_example-" without getting stuff that has more than just a single digit integer after the "-".
A value in the database will not have anymore than a single digit number (0-9) after the "-". So basically i need a query that searches for values that would look like this "test_example-[0-9]".
How can i do that? If this is confusing and needs clarification, please let me know. Thanks!
Here is the exact query that i am doing to ease some confusion:
SELECT MAC, NAME FROM HOST WHERE NAME LIKE (SELECT CONCAT(LEFT(NAME, LENGTH(NAME)-1), "%") FROM HOST WHERE MAC="some mac address");
Here is the working result ( thanks to swati ):
SELECT MAC, NAME FROM HOST WHERE NAME REGEXP CONCAT(LEFT(NAME, LENGTH(NAME)-1), "[0-9]+") AND MAC="some mac address";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该适用于 test_example-[0-9]。有关字符类和 REGEXP 的更多信息
使用给定的查询,它将是:
请注意,您发布的查询中有一个错误 - 您有两个 WHERE 子句。
That should work for test_example-[0-9]. More on Character Classes and REGEXP
With your given query, it would be:
Note there is an error in your posted query - you have two WHERE clauses.
您可以尝试使用 regexp,但我不这样做知道它的效率有多高。您可能想用代码而不是 SQL 来完成此操作。但仍然:
只需创建满足您需求的任何正则表达式即可。
You could try to use a regexp, though I don't know how efficient it will be. You might want to do it in code rather then in sql. but still:
Just create any regexp that satisfies your needs.
您可以使用下划线字符作为单个字符的通配符。
You can use an underscore character as the wildcard for a single character.