简体   繁体   English

强制脱节:漂亮查询?

[英]Mandatory disjoint: beautiful query?

I have a schema with table user (username, password, fullname, usertype) 我有一个带有表用户的模式(用户名,密码,全名,用户类型)

there are 4 types of users and for each there is a table with additional attributes for specific type: 有4种类型的用户,每种类型都有一个表,其中包含针对特定类型的其他属性:

  • individual(username (FOREIGN), education, work_since) 个人(用户名(FOREIGN),教育程度,工作时间开始)
  • corporation*(username (FOREIGN), headquarters, office, num_employees) 公司*(用户名(FOREIGN),总部,办公室,员工人数)
  • and a couple more... 还有更多...

there could be only 1 record in all the additional tables for user. 用户的所有其他表中可能只有1条记录。

I need to display all of the user information from user table and additional attribute table based on user type. 我需要根据用户类型显示用户表和其他属性表中的所有用户信息。

The first thing that came to mind was to first query user table, and then, based on type returned, query one of the related tables... but that would be too many queries, so I was wondering, is it possible to do it in a single query? 首先想到的是首先查询用户表,然后根据返回的类型,查询一个相关表...但是那将是太多的查询,所以我想知道是否有可能做到这一点在一个查询中?

Use left join : 使用left join

select u.*,
       (case when i.username is not null then 'individual'
             when c.username is not null then 'corporation'
        end) as usertype,
       i.education, i.work_since,
       c.headquarters, c.office, c.num_employees
from users u left join
     individual i
     on i.username = u.username left join
     corporation c
     on c.username = u.username;

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

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