[英]SQL Join query to join 2 tables to get desired output
I have 2 tables and need to join them to get a desired result. 我有2张桌子,需要将它们加入才能获得理想的结果。 I tried multiple types of joins but no luck. 我尝试了多种类型的联接,但是没有运气。 Please assist.Below is how my tables looks like: 请协助。以下是我的表格外观:
select * from t1 从t1选择*
ProductId, Sequence, Property
100, 1, Size
100, 2, Folder
100, 3, License
101, 1, Usage
101, 2, Duration
select * from t2 从t2选择*
SrNo, ProductId, Property, PropertyValue
1, 100, Size, 10GB
2, 100, Folder, /home/path
3, 101, Usage, Database
I need to join them to get the following result: 我需要加入他们才能获得以下结果:
SrNo, ProductId, Sequence, Property, PropertyValue
1 100 1 Size 10GB
1 100 2 Folder
1 100 3 License
2 100 1 Size
2 100 2 Folder /home/path
2 100 3 License
3 101 1 Usage Database
3 101 2 Duration
Below are the SQLs to reproduce the same tables: 以下是可重现相同表的SQL:
create table t1 (ProductId INT, Sequence INT, Property VARCHAR(255))
insert into t1 values(100,1,'Size');
insert into t1 values(100,2,'Folder');
insert into t1 values(100,3,'License');
insert into t1 values(101,1,'Usage');
insert into t1 values(101,2,'Duration');
create table t2 (SrNo INT, ProductId INT, Property VARCHAR(255), PropertyValue VARCHAR(255))
insert into t2 values(1,100,'Size','10GB');
insert into t2 values(2,100,'Folder','/home/path');
insert into t2 values(3,101,'Usage','Database');
Please assist how can I write my query? 请协助我如何编写查询?
SELECT
table2.SrNo,
table1.ProductId,
table1.Sequence,
table1.Property,
table2.PropertyValue
FROM t1 AS table1
JOIN t2 AS table2 ON table1.ProductId = table2.ProductId
Here you go 干得好
SELECT T2.SrNo, T2.ProductId, T1.Sequence, T1.Property, T3.PropertyValue
FROM T2
JOIN T1 ON T2.ProductID = T1.ProductID
LEFT JOIN T2 AS T3 ON T1.Property = T3.Property
The "problem" here is that you are treating T2 as two different tables. 这里的“问题”是您将T2视为两个不同的表。 When I first select from T2 I'm only selecting SrNo and ProductId to get a list of these "valid" values. 当我第一次从T2中选择时,我仅选择SrNo和ProductId以获得这些“有效”值的列表。 I then join them to T1. 然后,我将他们加入T1。 I then join back to T2 treating it as a lookup table for PropertyValue. 然后,我回到T2,将其作为PropertyValue的查找表。 Here I use a left join because not all combinations of Property and Sequence have a valid Property. 在这里我使用左连接,因为并非所有的Property和Sequence组合都具有有效的Property。
I "fixed" the code above based on the comment but a problem becomes clear. 我根据注释“修复”了上面的代码,但问题变得很明显。 In your example you show 在您的示例中,您显示
SrNo, ProductId, Sequence, Property, PropertyValue
1 100 1 Size 10GB
2 100 1 Size
I don't know why the 2nd row does not have a PropertyValue of 10GB 我不知道为什么第二行没有10GB的PropertyValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.