[英]Oracle SQL query - Get column value from alternate table
I am new to SQL and tried searching for responses in the forum but could not get any. 我是SQL的新手,尝试在论坛中搜索响应,但没有任何响应。
I have 3 tables from which i need to retrieve data. 我有3个表需要从中检索数据。
Table 1:
ID* | Field 1 | Field 2 |
1 | ABC | XYZ
Table 2:
ID-FK from table 1 | Company - Vendor | Company - Supplier
1 | 3 | 2
One of the company value could be null 公司价值之一可能为空
Table 3 (Company table)
Company ID | Company name
1 | Company A
2 | Company B
3 | Company C
Required output : 所需输出:
ID | Field 1 | Company - Vendor | Company - Supplier
1 | ABC | Company C | Company B
inner join mentioned in some posts did not work for me (Or i did not know how to work it) 一些帖子中提到的内部联接对我不起作用(或者我不知道如何工作)
Thanks in advance 提前致谢
select t1.ID,
t1."Field 1",
(select x."Company Name" from "Table 3" where "Company ID" = t2."Company - Vendor") as "Company - Vendor",
(select x."Company Name" from "Table 3" where "Company ID" = t2."Company - Supplier") as "Company - Supplier"
from "Table 1" t1
join "Table 2" t2 on t1.id = t2."ID-FK"
You probably need 2 left joins to get company and vendor so given 您可能需要2个左联接才能得到公司和供应商
drop table if exists table1,table2,table3;
create table table1(ID int, Field1 varchar(3), Field2 varchar(3));
insert into table1 values
(1 , 'ABC' , 'XYZ');
create table Table2(IDFK int, CompanyVendor int, CompanySupplier int);
insert into table2 values
(1 , 3 , 2),
(1 , 3 , null),
(1 , null , 2),
(1 , 4 , 5),
(1 , 1 , 2)
;
create table Table3 (CompanyID int, name varchar(20));
insert into table3 values
(1 , 'Company A'),
(2 , 'Company B'),
(3 , 'Company C');
This query 这个查询
select t1.*,t2.companyvendor,t3.name Vendorname,
t2.companysupplier,t4.name Suppliername
from table1 t1
join table2 t2 on t2.idfk = t1.id
left join table3 t3 on t3.CompanyID = t2.companyvendor
left join table3 t4 on t4.CompanyID = t2.companysupplier
;
Yields this result 产生这个结果
+------+--------+--------+---------------+------------+-----------------+--------------+
| ID | Field1 | Field2 | companyvendor | Vendorname | companysupplier | Suppliername |
+------+--------+--------+---------------+------------+-----------------+--------------+
| 1 | ABC | XYZ | 1 | Company A | 2 | Company B |
| 1 | ABC | XYZ | 3 | Company C | 2 | Company B |
| 1 | ABC | XYZ | NULL | NULL | 2 | Company B |
| 1 | ABC | XYZ | 3 | Company C | NULL | NULL |
| 1 | ABC | XYZ | 4 | NULL | 5 | NULL |
+------+--------+--------+---------------+------------+-----------------+--------------+
5 rows in set (0.00 sec)
BTW never use hyphen (-) as an entity name and don't use whitespace. BTW永远不要使用连字符(-)作为实体名称,也不要使用空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.