简体   繁体   English

PostgreSQL将表联接到几列

[英]Postgresql join tables to several columns

I have a list of students' name called table Names and I want to find their categories from another table called Categories as below: 我有一个名为表名称的学生姓名列表,我想从另一个名为类别的表中找到他们的类别,如下所示:

Class_A    Class_B    Class_C  Class_D  Category
Sam                   Adam              High
            Sarah                       Medium
James                                   High
Emma        Simon               Nick    Low

My solution is to do a left join but students name from first table should be matching with one of four columns so I am not sure how to write queries. 我的解决方案是进行左联接,但第一个表中的学生姓名应与四列之一匹配,因此我不确定如何编写查询。 At the moment my query is just matching to Class_A while I need to check all categories and if the student's name exist, return category. 目前,我的查询仅与Class_A匹配,而我需要检查所有类别,如果学生的姓名存在,则返回类别。 (Note: some rows have more than one student's name) (注意:有些行有多个学生的名字)

SELECT Names.name, Categories.Category 
FROM Names
   LEFT JOIN Categories ON Names.name = Categories.Class_A; 

Table Names looks like this: 表名看起来像这样:

Name
----
Emma
Nick
James
Adam
Jack
Sarah

And I am expecting an output as below: 我期望输出如下:

Name     Category
----     ----
Emma     Low
Nick     Low
James    High
Adam     High
Jack     -
Sarah    Medium

Try this using OR in on clause: 尝试使用on子句中的OR:

SELECT Names.name, coalesce(Categories.Category,'-') as category 
FROM Names
   LEFT JOIN Categories ON Names.name = Categories.Class_A or Names.name = Categories.Class_B or Names.name = Categories.Class_C or Names.name = Categories.Class_D

I would be inclined to unpivot the first table. 我倾向于取消第一张桌子。 This looks like: 看起来像:

select n.name, c.category
from name n left join
     (categories c cross join lateral
      (values (c.class_a), (c.class_b), (c.class_c), (c.class_d)
      ) v(name)
     )
     on n.name = v.name
where v.name is not null;

Although you can also solve this using in (or or ) in the on clause, that may produce a much less efficient execution plan. 虽然你也可以解决这个使用in (或or )在on条款,即可能产生的效率低得多的执行计划。

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

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