mysql - 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)
编辑:
我用逗号更改了连字符
解决方案
在关系数据库中,没有“列表”或“数组”。使用一组行,给定列中的每行一个值。
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;
推荐阅读
- azure - 检索到的 Azure AD Web 应用程序的 OAuth2.0 授权码是否过期?
- javascript - 检查 chrome 网络中的标头时注入.JS 文件
- java - 在 JSP JSTL 中添加 1 秒
- html - 更改angularjs数据网格中按钮的标题
- java - Java 8 Predicate - 为什么不能加入通配符泛型谓词?
- javascript - for循环中的索引对象,单击时保留信息
- elasticsearch - Filebeat 没有在 Elasticsearch 中创建索引
- javascript - 模态没有正确关闭
- html - Notepad++中的文字如何去掉红色下划线?
- git - 使用 gnu make 提取 6 个字符的子字符串