php - 这个 MySQL 查询是最好的主意吗?

标签 php mysql optimization

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

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

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

选择 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 ...

最佳答案

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'

关于php - 这个 MySQL 查询是最好的主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/347851/

相关文章:

javascript - Wordpress Contact-form 7 - 使用 Jquery 的预订表单功能

PHP/MySQL 更新复选框选择到数据库 2

PHP 在某些点拆分字符串

java - 拥有大量小方法是否有助于 JIT 编译器优化?

php - 如何使用带有mysql的php codeigniter压缩数据

php - 检查文本是否包含 URL

javascript - 我应该将数据存储在 JSON 文件中还是 MySQL 数据库中?

mysql 多重连接与多重查询

Python 名册优化器

algorithm - 如何有效地多样化 Dijkstra 算法(同时保留最短路径)?