【问题标题】:Get record from one table where id is in second table array in mysql json从一个表中获取记录,其中 id 在 mysql json 中的第二个表数组中
【发布时间】:2019-11-15 02:42:57
【问题描述】:

我的 MySQL 数据库中有两个表,结构如下。

table roles
+----+-----------+---------------------+
| id | name      | description         |
+----+-----------+---------------------+
|  1 | Owner     | Owner of a workspace|
|  2 | Biller    | Biller of workspace |
|  3 | Member    | Member of Workspace |
+----+-----------+---------------------+


table user which contain an array of roles id in JSON data type.
+----+-----------+---------------------+
| id | name      | roles               |
+----+-----------+---------------------+
|  1 | xyz       | [1,2]               |
+----+-----------+---------------------+

现在,表 user 包含一个角色 id 数组,我想在条件下加入两个表,role.id 在 user.roles 中。例如,我想得到一些这样的数据:

select * from roles join user on roles.id in user.roles where user.id=1;

+----+-----------+---------------------+
| id | name      | description         |
+----+-----------+---------------------+
|  1 | Owner     | Owner of a workspace|
|  2 | Biller    | Biller of workspace |
+----+-----------+---------------------+

【问题讨论】:

  • 从每个表中添加至少 2-3 行
  • “我该怎么做?” 您可以从给我们真实的示例数据和预期结果开始。见Why should I provide a Minimal Reproducible Example for a very simple SQL query?
  • 为什么不呢,创建一个角色表并与用户表建立关联..然后您可以轻松检查它们。
  • "表用户包含一个角色 ID 数组"。这不可能。 MySQL 没有数组类型。您的问题不清楚。

标签: mysql sql json database


【解决方案1】:

这样效果更好

select * from roles where FIND_IN_SET(id,(select Replace(Replace(roles,']',''),'[','') from user));

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 2020-02-20
    • 2021-11-26
    • 1970-01-01
    • 2018-07-11
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多