Jonathan
Jonathan

Reputation: 3

Query Sql Like String

I need help for sql query LIKE. Value for column in database is same below:

 record 1 : "3,13,15,20"
 record 2 : "13,23,14,19"
 record 3 : "3,14,15,19,20"......

for now I want to get the most accurate record with a value of 3 This is my query :

SELECT * FROM accounts where type like '%3%' 

This query will find all record with value exist is '3' eg: 13,23 .... And It does not solve my problem.

Upvotes: 0

Views: 51

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

Try this:

SELECT *
FROM accounts
WHERE CONCAT(',', type, ',') LIKE '%,3,%';

enter image description here

Demo

This trick places commas around the end of the type CSV string, so that we all we have to do is then check for ,3, anywhere in that string.

By the way, it is generally not desirable to store CSV data like this in your SQL tables. Instead, consider normalizing your data and storing those CSV values across separate rows.

Upvotes: 3

Related Questions