通过连接 DB2 中的表来查询数据
Query data by joining tables in DB2
这些是我的 table 详细信息:
Table1
id name
----------------
101 syed
102 shaik
103 khan
Table2
l_id sup_id
-----------------
101 102 ----> 102 is supervisor of 101
102 103 ----> 103 is supervisor of 102
103 104 ----> 104 is supervisor of 103
我的预期输出是获取人员的所有数据以及他们的主管 ID 和姓名。
id name sup_id sup_name
------------------------------
101 syed 102 shaik
102 shaik 103 khan
103 khan --> Since 104 is not available in the master table (table 1), it should have as empty values.
在 table-1 中,我有三行 101,102,103,这是一个 master table,它将保存所有人的基本信息。 Table 2 由主管登录 ID 及其下属 ID 组成。 table1 和 table2 之间的公共列是 id & l_id。所以,我正在尝试按如下方式提取数据以获取详细信息。
我的查询如下
select t1.id,t1.name, sup_id,t2.name as sup_name
from table2 t
join table1 t1 on t1.id=t.l_id
join table1 t2 on t2.id=t.sup_id
我能够获得前 2 行,因为他们在 table 1 中有主管 ID,但不是第 3 行
任何想法将不胜感激
person id - person name - supervisor id - supervisor name
试试这个:
select t1.id,t1.name, sup_id,t2.name as sup_name
from table2 t
left join table1 t1 on t1.id=t.l_id
left join table1 t2 on t2.id=t.sup_id
JOIN
/INNER JOIN
不会return条在JOIN
table.
中没有对应的记录
您可能需要检查 joins 的不同类型。
如果你真的想使用内连接,你也可以使用子查询。
select b.id,b.name,b.sup_id,t2.name
(select t.id,sup_id,t1.name 作为名称
从表 2 t
t1.id=t.l_id 上的内部联接表 1 t1
) 乙
在 t2.id=b.sup_id
左连接表 1 t2
这些是我的 table 详细信息:
Table1
id name
----------------
101 syed
102 shaik
103 khan
Table2
l_id sup_id
-----------------
101 102 ----> 102 is supervisor of 101
102 103 ----> 103 is supervisor of 102
103 104 ----> 104 is supervisor of 103
我的预期输出是获取人员的所有数据以及他们的主管 ID 和姓名。
id name sup_id sup_name
------------------------------
101 syed 102 shaik
102 shaik 103 khan
103 khan --> Since 104 is not available in the master table (table 1), it should have as empty values.
在 table-1 中,我有三行 101,102,103,这是一个 master table,它将保存所有人的基本信息。 Table 2 由主管登录 ID 及其下属 ID 组成。 table1 和 table2 之间的公共列是 id & l_id。所以,我正在尝试按如下方式提取数据以获取详细信息。
我的查询如下
select t1.id,t1.name, sup_id,t2.name as sup_name
from table2 t
join table1 t1 on t1.id=t.l_id
join table1 t2 on t2.id=t.sup_id
我能够获得前 2 行,因为他们在 table 1 中有主管 ID,但不是第 3 行
任何想法将不胜感激
person id - person name - supervisor id - supervisor name
试试这个:
select t1.id,t1.name, sup_id,t2.name as sup_name
from table2 t
left join table1 t1 on t1.id=t.l_id
left join table1 t2 on t2.id=t.sup_id
JOIN
/INNER JOIN
不会return条在JOIN
table.
您可能需要检查 joins 的不同类型。
如果你真的想使用内连接,你也可以使用子查询。
select b.id,b.name,b.sup_id,t2.name (select t.id,sup_id,t1.name 作为名称 从表 2 t t1.id=t.l_id 上的内部联接表 1 t1 ) 乙 在 t2.id=b.sup_id
左连接表 1 t2