I have a user id that I would like to find if this id existed in a separated list with hyphen, using a bind method:
I have 2 issues:
1- The correct SQL query,
2- How to bind the value.
Table structure:
mysql> SELECT dash_cat_id, dash_users_cats FROM dash_cats;
+-------------+-----------------+
| dash_cat_id | dash_users_cats |
+-------------+-----------------+
| 1 | 2 |
| 2 | 1,2 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1,2,3 |
| 6 | 1,2,3 |
| 7 | 1,2,3 |
| 8 | 1,2,3 |
+-------------+-----------------+
8 rows in set (0.00 sec)
$userID = 2; // this might be changed to 1 OR 3, it depends of the user
Then I would like to retrieve all dash_users_cats that the userID is 2 as an example;
I used this query, but it seems to be wrong:
mysql> SELECT dash_cat_id, REPLACE(dash_users_cats, '-', ',') as dashRep from dash_cats WHERE FIND_IN_SET(2, dash_users_cats);
+-------------+---------+
| dash_cat_id | dashRep |
+-------------+---------+
| 1 | 2 |
| 4 | 2 |
+-------------+---------+
2 rows in set (0.00 sec)
EDIT:
I changed the hyphen with the comma
You should normalize your tables by storing single user_cat value against each user_id. Refer to @Bill Karwin's answer. However, you can still make your current solution work by replacing comma with hyphen in the WHERE
clause,
SELECT dash_cat_id,
REPLACE(dash_users_cats, '-', ',') as dashRep
FROM dash_cats
WHERE FIND_IN_SET(2, REPLACE(dash_users_cats, '-', ','))