0

I'm using below sql query for search values from db, but when I search 'study' it will returns the values 'caese-study', 'get-study-materials' as well. How can I use a query to search exact contains withing string column?

$names = 'study'; and the names column has values like comma separated, Ex: 'study, abc, new' so I need to search within that too

SELECT * FROM datatitle WHERE  names LIKE '%$names %' ;

SELECT * FROM datatitle WHERE  names regexp '(^|[[:space:]])$names([[:space:]]|$)';

I try with above two queries but didnt work as expect, pls advice?

8
  • names="study"? Commented Dec 30, 2018 at 15:44
  • stop using LIKE use =, e.g SELECT * FROM datatitle WHERE names= '$names' ; Commented Dec 30, 2018 at 15:45
  • @Curious_Mind names column has comma separated data so will it work for that? Commented Dec 30, 2018 at 15:50
  • 1
    I've reopened this. Hint: You'll need to use IN() for this or possibly FIND_IN_SET() but unsure on the latter. Commented Dec 30, 2018 at 15:52
  • 2
    Should probably normalize the table. See stackoverflow.com/questions/3653462/… Commented Dec 30, 2018 at 15:57

1 Answer 1

2

You should not be storing comma-separated values in a column. You should be using a junction/association table. You should fix the data model, if you can.

However, sometimes we cannot control other people's really bad decisions. MySQL has find_in_set():

SELECT dt.*
FROM datatitle dt
WHERE find_in_set(?, names) > 0;

Note that I have replaced the constant $names with a parameter. You should learn to use parameters to pass values into queries.

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

Comments

Your Answer

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