简体   繁体   中英

How I can CONCAT vertical lines from MySQL using PHP

If have following problem. I cannot get values from MySQL when I have them separated with |

I have following string:

SELECT * FROM user WHERE CONCAT(',', category, ',') REGEXP ',(lc_8|swimming),'

and this string only works when in my MySQL I have column category with value lc_8,swimming,

How I can change string above to get same values but if in column I have lc_8|swimming| ?

| is a special character in regexps. You would need to escape it, like \\| . Try:

SELECT * FROM user WHERE CONCAT(',', category, ',') REGEXP ',(lc_8\|swimming),'

Characters that need escaping in regexes are as follows:

* ? + [ ( ) { } ^ $ | \

If you really want to match the parentheses in your example, you would need to quote them as well.

( and | have a special meaning in a regular expression, you need to escape them.

SELECT *
FROM user
WHERE CONCAT(',', REPLACE(category, '|', '\\|'), ',') REGEXP ',\(lc_8\|swimming\),'

But if you're searching a comma-delimited list, it would be better to use the function designed for that:

SELECT * FROM user
WHERE FIND_IN_SET('(lc_8|swimming)', category)

Even better would be to not store comma-delimited lists in the first place, but put the categories in a separate table with one row for each category.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM