首页 > 解决方案 > MySQL 在分隔的连字符列表中查找值

问题描述

我有一个用户 ID,我想使用绑定方法查找此 ID 是否存在于带有连字符的分隔列表中:

我有两个问题

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)

编辑:

我用逗号更改了连字符

标签: mysqlpdobind

解决方案


在关系数据库中,没有“列表”或“数组”。使用一组行,给定列中的每行一个值。

mysql> SELECT dash_cat_id, dash_users_cats FROM dash_cats;
+-------------+-----------------+
| dash_cat_id | dash_user_id    |
+-------------+-----------------+
|           1 | 2               |
|           2 | 1               |
|           2 | 2               |
|           3 | 1               |
|           4 | 2               |
|           5 | 1               |
|           5 | 2               |
|           5 | 3               |
|           6 | 1               |
|           6 | 2               |
|           6 | 3               |
|           7 | 1               |
|           7 | 2               |
|           7 | 3               |
|           8 | 1               |
|           8 | 2               |
|           8 | 3               |
+-------------+-----------------+

现在您可以轻松搜索特定用户:

SELECT * FROM dash_cats WHERE dash_user_id = 2;

推荐阅读