簡體   English   中英

SQL 其他表中有父子關系的Parent狀態

[英]SQL Status of Parent with Parent-Child relationship in other table

在表 1 中,我有狀態記錄。

鑰匙 地位 組合 家長
鍵1 A B C D 1個 0
鑰匙2 A B C D 1個 0
鑰匙3 XYZ 1個 0
鑰匙4 XYZ 1個 1個
鍵5 QWERT 1個 1個
鍵6 A B C D 0 0

在表 2 中,我有父子關系

鑰匙 父鍵 查看
鍵1 鑰匙4 一種
鑰匙2 鑰匙4
鑰匙3 鍵5 一種
鑰匙4 鑰匙4
鍵5 鍵5 一種

我正在尋找的結果是一張包含 ParentStatus 的表格。 但僅當 Table1.Combi = 1 且 Table1.Parent = 0 且 Table2.Check = A 時。像這樣:

鑰匙 父母身份
鍵1 XYZ
鑰匙2
鑰匙3 QWERT
鑰匙4
鍵5
鍵6

我們可以在連接條件中使用check_ = 'A'等條件。 如果我們使用 where 那么這些行將不會被返回。

 create table table1 (key_ varchar(10), status varchar(10), combi int, parent int); insert into table1 values ('key1','ABCD',1,0), ('key2','ABCD',1,0), ('key3','XYZ',1,0), ('key4','XYZ',1,1), ('key5','QWERT',1,1), ('key6','ABCD',0,0); create table table2(key_ varchar(10), ParentKey varchar(10), Check_ char); insert into table2 values ('key1','key4','A'), ('key2','key4','B'), ('key3','key5','A'), ('key4','key4','B'), ('key5','key5','A');
 select t.key_, ttt.status Parent_Status from table1 t left join table2 tt on t.key_ = tt.Key_ and Check_ = 'A' and parent = 0 left join table1 ttt on tt.ParentKey = ttt.key_ and t.combi = 1
 鍵_ |  parent_status:--- |:------------ key1 |  XYZ鍵2 |  null 鍵3 |  QWERT key4 |  null鍵5 |  null鍵6 |  null

db<> 在這里擺弄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM