2

A few months ago i asked the question below.

My question.

However, i have ran into a problem.

When i use this query:

SELECT MAC, NAME FROM DB.HOST WHERE NAME REGEXP (SELECT CONCAT(LEFT(NAME, LENGTH(NAME)-1), "[0-9]+") FROM DB.HOST WHERE MAC="some mac");

If the mac address is resolved to "example_224-06-55" and their is another element in the DB named "example_224-06-55-00" they will both show up as a result of this query. I only want "example_224-06-55" to show up as a result of that query.

The size of the name's will vary, the examples are just examples.

I am having a really hard time figuring this out, any help is greatly appreciated!

THE WORKING QUERY:

SELECT MAC, NAME FROM DB.HOST WHERE NAME REGEXP (SELECT CONCAT(LEFT(NAME, LENGTH(NAME)-1), "[0-9][[:>:]]") FROM DB.HOST WHERE MAC="some mac");

3 Answers 3

2

MySQL supports a special word boundary pattern [[:>:]] to solve this.

SELECT MAC, NAME FROM DB.HOST 
WHERE NAME REGEXP (
 SELECT CONCAT(LEFT(NAME, LENGTH(NAME)-1), '[0-9]+[[:>:]]') 
 FROM DB.HOST 
 WHERE MAC='some mac'
);

See http://dev.mysql.com/doc/refman/5.1/en/regexp.html, the word boundary patterns are documented near the bottom of the page.

ps: Use single-quotes for string literals in SQL. Double-quotes are for delimited identifiers.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much sir, that worked great! However, for it to work, i did have to remove the "+".
2

Update your regular expression that exactly you want.

SELECT MAC, NAME FROM DB.HOST 
 WHERE NAME REGEXP 
  (SELECT CONCAT(LEFT(NAME, LENGTH(NAME)-1), "_[0-9]+-[0-9]+-[0-9]+$") 
    FROM DB.HOST WHERE MAC="some mac");

1 Comment

It can be of a varrying length, that was just an example.
1

If you want to write a pattern for strings ending with numbers like 'xxx-xx-xx' instead of "[0-9]+" you can use "\d\d\d-\d\d-\d\d"

4 Comments

The size can be different every time. It might not always be only 7 digits, it might be 9 next time, or 5.
Then please clarify why the string "example_224-06-55-00" does not satisfy your requirements. Is it about the trailing zeroes ?
Because if the "some mac" is resolved to a name "example_224-06-55" and their exists another name in the DB "example_224-06-55-00" they will both show up. I only want "example_224-06-55" to show up.
Thanks, just didn't get what the exact problem was at once :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.