【问题标题】:MySQL find value in a separated hyphen listMySQL 在分隔的连字符列表中查找值
【发布时间】: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)

编辑:

我把连字符换成了逗号

【问题讨论】:

标签: mysql pdo bind


【解决方案1】:

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

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;

【讨论】:

    【解决方案2】:

    您应该通过针对每个 user_id 存储单个 user_cat 值来规范您的表。请参阅@Bill Karwin 的回答。但是,您仍然可以通过在 WHERE 子句中将逗号替换为连字符来使当前的解决方案发挥作用,

    SELECT dash_cat_id,
    REPLACE(dash_users_cats, '-', ',') as dashRep
    FROM dash_cats
    WHERE FIND_IN_SET(2, REPLACE(dash_users_cats, '-', ','))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-04
      • 2019-06-18
      • 2013-04-30
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2021-02-14
      相关资源
      最近更新 更多