4

I have mysql table values like

1-2

1-2-3

1-4-5

1-4-5-12-15

15-45-75

1-5-15-25-35-55

55-65-75

I want to select which rows have number 5(not 15 or 25 or 35).

I have tried with LIKE query but it gives all 5 value contains rows(including 15, 35, 45,55).

SELECT ... WHERE linkage LIKE '%5%'

I think we can do it through REGEXP. Can you help me for it?

1
  • 1
    Regular expressions are terribly inefficient in every dbms out there. Don't do it. Just use a simple query that can take advantage of your indexes. Commented Aug 31, 2012 at 6:33

2 Answers 2

7

You can do this using FIND_IN_SET:

SELECT ... 
WHERE FIND_IN_SET(5, REPLACE(linkage,'-',','));

Example @ sqlfiddle

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

Comments

2

try

SELECT ... WHERE concat('-',linkage,'-') LIKE '%-5-%'


SQL Fiddle Demo

5 Comments

5 could appear at the start, middle, or end of the set. You need to match all three cases. Consider these values: 1-5-2, 5-2-1, 1-2-5. The edit I submitted will cover these.
@dodexahedron: I am concatinating,a '-' at both ends of the column.. please check the updated answer
That makes indexes useless, though. Shorter SQL is not always better SQL. While your query will certainly do it, it's better to do the ORs with the explicit cases, because one of the cases can use an index scan and the others will be table scans. Yours should result in a table scan every time. Worth testing to see how the query optimizer runs it, but I have a feeling the naive way of ORs for each of the 3 cases will outperform.
@dodexahedron: Good thinking.. but the moment we use a % at the beginning of the search string , index will not be used.. so query with OR also will do table scan..
You're absolutely correct. Chalk it up to trying to think at 3AM... There's no way to do what he wants without a table scan, so your example is probably the simplest. Call me crazy, but I don't trust that FIND_IN_SET function to be better than your solution. ;)

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.