我有三张桌子。
我想使用“一个” sql语句将以下值插入到table3.stat中。
1.从table0,table2中选择状态,其中table0.serial = table2.num
2.从table1,table2中选择条件,其中table1.ID = table2.num
postgresql可以吗?
table0:
| serial | status | |
|--------|--------|---|
| a22 | good | |
| a33 | bad | |
| a11 | bad | |
table1:
| ID | condition | |
|-----|-----------|---|
| a00 | awesome | |
| a44 | bad | |
| a11 | bad | |
table2:
| num | | |
|------|---|---|
| a00 | | |
| a44 | | |
| a22 | | |
| a33 | | |
table3:
| num | stat |
|-----|------|
| | |
| - | - |
desired result:
| num | stat |
|-----|-------|
| a22 | good |
| a33 | bad |
| a00 |awesome|
| a44 | bad |
答案 0 :(得分:0)
您似乎在以
查找查询select table2.num, table0.status
from table0
INNER JOIN table2 ON table0.serial=table2.num
INNER JOIN table1 ON table1.ID=table2.num
insert into table3 (num, stat)
select table2.num, table0.status
from table0
INNER JOIN table2 ON table0.serial=table2.num
INNER JOIN table1 ON table1.ID=table2.num
或者,如果列不总是匹配,则可以使用左连接(如Juan Carlos Oropeza所建议)
select table2.num, table0.status
from table0
LEFT JOIN table2 ON table0.serial=table2.num
LEFT JOIN table1 ON table1.ID=table2.num
insert into table3 (num, stat)
select table2.num, table0.status
from table0
LEFT JOIN table2 ON table0.serial=table2.num
LEFT JOIN table1 ON table1.ID=table2.num
更新
与您的评论有关
对于内部联接,表1中没有有效值。因此,对于左联接,此结果不返回任何结果。对于左联接,当不匹配时,左联接也返回值,那么您也将返回null值。唯一工作条件
根据您的提琴演奏
可能是
select table2."num", table0."status"
from table0
INNER JOIN table2 ON table0."serial"=table2."num"
LEFT JOIN table1 ON table1."ID"=table2."num";
答案 1 :(得分:0)
即使有两个选择,也使用UNION ALL
只是一个语句
INSERT INTO table3 ("num", "stat")
select table2."num", table0."status"
from table0
JOIN table2 ON table0."serial"=table2."num"
UNION ALL
select table2."num", table1."condition"
from table1
JOIN table2 ON table1."ID"=table2."num"
;