简体   繁体   English

这是MySQL查询的最佳主意吗?

[英]Is this MySQL query the best idea?

The project I'm working on has two type of accounts, " people " and " companies ". 我正在处理的项目有两种类型的帐户,“ people ”和“ companies ”。

I hold a single " users " table with all the accounts and just the basic info needed for login (email, pass, etc), and two other tables " user_profiles " (regular people) and " company_profiles " (companies) that hold more specific columns for each type, both of the tables linked to the general " users " table via a " profile_user_id " column. 我拥有一个带有所有帐户的“ users ”表,仅包含登录所需的基本信息(电子邮件,通行证等),还有另外两个表“ user_profiles ”(常规人员)和“ company_profiles ”(公司)拥有更具体的信息每种类型的列,两个表都通过“ profile_user_id ”列链接到常规“ users ”表。

But, whenever I want to list users that can be both people and companies, I use : 但是,每当我要列出既可以是个人又可以是公司的用户时,我会使用:

" 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 ". 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 ”。

When I list these users I know whether they're people or companies by the " user_type ". 当我列出这些用户时,我通过“ user_type ”知道他们是个人还是公司。

Is my approach using concat_ws the right (optimal) one? 我使用concat_ws的方法是否正确(最佳)? I did this instead of select -ing every *_name to avoid returning more columns than necessary. 我这样做是为了避免返回*_name列,而不是对每个*_name select -ing。

Thanks 谢谢

EDIT: the query above continues like: from users left join user_profiles on ... left join company_profiles on ... 编辑:上面的查询继续像: from users left join user_profiles on ... left join company_profiles on ...

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'

Does the query you already have work? 您已经查询成功了吗? Is it that you're experiencing performance issues from using this approach already? 您是否已经通过使用这种方法遇到性能问题?

Unless using the above query is taking way longer than you're expecting it to be or is causing issues in the software calling this information, this might be pre-mature optimization. 除非使用上面的查询花费的时间比您预期的要长,或者导致调用此信息的软件出现问题,否则这可能是过早的优化。

One thing to note though, your first use of CONCAT_WS doesn't have a seperator, so the company name is going to be merged with the person's name. 不过要注意一点,您第一次使用CONCAT_WS时没有分隔符,因此公司名称将与该人的姓名合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM