我是SQL新手并尝试在论坛中搜索回复,但却无法获得任何回复。
我有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
公司价值之一可能为空
Table 3 (Company table)
Company ID | Company name
1 | Company A
2 | Company B
3 | Company C
必需的输出:
ID | Field 1 | Company - Vendor | Company - Supplier
1 | ABC | Company C | Company B
某些帖子中提到的内部联接对我不起作用(或者我不知道如何使用它)
提前致谢
答案 0 :(得分:0)
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"
答案 1 :(得分:0)
您可能需要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');
此查询
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
;
产生此结果
+------+--------+--------+---------------+------------+-----------------+--------------+
| 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从不使用连字符( - )作为实体名称,也不使用空格。