如何在postgres中将两个select语句作为两列

时间:2019-07-09 10:08:20

标签: mysql postgresql

很简单,但我找不到它。

我有以下三个表

select * from student;

 id1 | name1  
 ----+--------
   1 | ishi 
   2 | sangee


select * from domain;

 id2 | name2  
-----+--------
   1 | python
   2 | scala
   3 | java
   4 | c#

select * from mainpk;

 id1 | id2 
-----+-----
   1 |   1
   1 |   2
   1 |   3
   2 |   3
   2 |   4

我有两个选择语句:

select student.name1 from student join mainpk on student.id1 = mainpk.id1;

结果:

 name1  
--------
 ishi
 ishi
 ishi
 sangee
 sangee

select domain.name2 from domain join mainpk on domain.id2 = mainpk.id2;`**

结果:

 name2  
--------
 python
 scala
 java
 java
 c#

如何将这两列合并为一个表。任何建议都是可以接受的。

预期输出为:

name1  | name2 
-------+-------
ishi   | python  
ishi   | scala  
ishi   | java  
sangee | java
sangee | c# 

1 个答案:

答案 0 :(得分:0)

JOINmainpk表结果一起使用,以下查询将返回预期结果:

select st.name1, dm.name2
from mainpk ms
join student st on st.id1 = ms.id1 
join domain dm on dm.id2 = ms.id2

请找到working demo on db<>fiddle