【问题标题】:Fetch names from another table, the ids of which are stored in a column in csv format in the primary table从另一个表中获取名称,其 id 存储在主表中 csv 格式的列中
【发布时间】:2013-09-17 09:46:36
【问题描述】:

我有两个表 - 用户和模块。

在模块表中,我有两列 - module_id 和 module_name。

用户表有一个名为 user_modules 的列,我在其中存储了他可以以 csv 格式访问的模块。

例如。模块表中有两个模块

module_id    module_name

1            Manage Books
2            Manage Videos 

典型用户的 user_modules 列(在用户表中)看起来像这样

user_modules

1,2

现在我用来获取 module_name 的查询是

"Select module_name from modules where module_id in (Select user_modules from user where user_id = 1)" - 输出:管理书籍

这仅返回第一个模块的名称。

另一方面,这些查询工作得非常好 -

“从 module_id 在 (1,2) 中的模块中选择 module_name” - 输出:管理书籍、管理视频

“从 user_id = 1 的用户中选择 user_modules” - 输出:1,2,3

如何在单个查询中获取所有模块名称?

【问题讨论】:

    标签: mysql


    【解决方案1】:
    select user.user_id, module_name from module 
    inner join user on find_in_set(module.module_id, user.user_modules) is not null
    

    应该可以。如果用户 ID(字符串)在 user_modules(字符串)中,则 find_in_set 返回位置。如果不是,则返回 null。

    或修改您的查询

    'Select module_name from modules where module_id in (Select user_modules from user where user_id = 1)" - 输出:管理书籍

    到:

    Select module_name from modules 
    where 
    find_in_set(module_id, (Select user_modules from user where user_id = 1)) is not null
    

    【讨论】:

    • 没问题;不幸的是,我也不得不处理串联的 ID
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多