【发布时间】:2021-06-20 12:25:43
【问题描述】:
我有一个用户 ID,我想使用绑定方法来查找此 ID 是否存在于带有连字符的分隔列表中:
我有 2 个问题:
1- 正确的 SQL 查询,
2- 如何绑定值。
表结构:
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
那我以检索所有userID为2的dash_users_cats为例;
我使用了这个查询,但似乎是错误的:
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)
编辑:
我把连字符换成了逗号
【问题讨论】:
-
规范化你的架构。见"Is storing a delimited list in a database column really that bad?"(剧透:是的。)。
-
那么,如果我用逗号分隔,那怎么查询呢?
-
您可能误解了...不要不要使用带有分隔列表的字符串根本,不管分隔符、逗号或破折号或其他什么...
-
所以我应该使用这样的数组[1,2,3]?