【问题标题】:Is this MySQL query the best idea?这个 MySQL 查询是最好的主意吗?
【发布时间】:2016-12-23 23:50:38
【问题描述】:

我正在处理的项目有两种类型的帐户,“people”和“companies”。

我持有一个“users”表,其中包含所有帐户以及登录所需的基本信息(电子邮件、密码等),以及另外两个表“user_profiles”(普通人)和“@987654325 @"(公司)为每种类型保存更具体的列,这两个表都通过“profile_user_id”列链接到一般的“users”表。

但是,每当我想列出既可以是个人也可以是公司的用户时,我会使用:

select user_id, user_type, concat_ws('', concat_ws(' ', user_profiles.profile_first_name, user_profiles.profile_last_name), company_profiles.profile_company_name) as user_fullname”。

当我列出这些用户时,我通过“user_type”知道他们是个人还是公司。

我使用concat_ws 的方法是正确的(最佳)方法吗?我这样做而不是 select-ing 每个 *_name 以避免返回不必要的列。

谢谢

编辑:上面的查询继续如下:from users left join user_profiles on ... left join company_profiles on ...

【问题讨论】:

    标签: php mysql optimization


    【解决方案1】:
    select
     u.user_id, u.user_type, concat_ws(profile_first_name + profile_last_name) as full_name
    from 
     users u, user_profiles up
    where u.key = up.key
     and u.user_type = 'user'
    
    union
    
    select
     u.user_id, u.user_type, concat_ws(profile_first_name + profile_last_name) as full_name
    from 
     users u, company_profiles cp
    where u.key = cp.key
     and u.user_type = 'company'
    

    【讨论】:

    • 考虑到两个profile 表具有不相交的users 集,因为用户可以是personcompany,UNION 解决方案是否比我最初的 concat 想法更好?
    • 运行解释计划并查看关系数据库用于处理集的差异
    • 两个查询最终都做了 2 次连接。恕我直言,这个更明确和易于理解。
    【解决方案2】:

    您已有的查询是否有效?是不是您已经在使用这种方法时遇到了性能问题?

    除非使用上述查询花费的时间比您预期的要长,或者导致调用此信息的软件出现问题,否则这可能是未成熟的优化。

    但需要注意的是,您第一次使用 CONCAT_WS 时没有分隔符,因此公司名称将与人名合并。

    【讨论】:

    • 我上面写的查询已经有效,我只是质疑它的最优性。第一个 concat_ws 没有分隔符的原因是,在将 users 表左连接到 user_profiles 和 company_profiles 后,我实际上连接了两列,其中我 知道 为 NULL。
    • 因此,如果您不希望单个用户条目同时存在 user_profile 和 company_profile 信息来执行“斯蒂芬科尔伯特,喜剧中心”之类的操作,那么 MSON 的查询将是最好的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多