我有以下3张桌子。
PROP_MASTER
--------------------
BORO
BLOCK
LOT
COL1
COL2
COL3
TABLE2
-------------
BORO
BLOCK
LOT
COL4
TABLE3
-------------
BORO
BLOCK
LOT
COL5
在一个查询中我想得到
Boro
Block
Lot
COL1
COL2
COL3
COL4
COL5
但是,如果两个表2中的同一个BORO,BLOCK和LOT不存在记录,则COL4应该返回0,如果表3中不存在记录,则COL5应该为零。
我如何加入这3个表。
Select B.BORO,B.BLOCK,B.LOT,B.COL1,B.COL2,B.COL3
FROM PROP_MASTER B, TABLE2 T2, TABLE3 T3
WHERE B.BORO=T2.BORO AND B.BORO=T3.BORO AND
B.BLOCK=T2.BLOCK AND B.BLOCK=T3.BLOCK AND
B.LOT=T3.LOT AND B.LOT=T3.LOT
答案 0 :(得分:1)
我认为您最好的方法是根据共同的属性(BORO,BLOCK和LOT)将LEFT JOIN
Table2和Table3放入您的PROP_MASTER
,然后使用COALESCE
:>
SELECT
PROP_MASTER.BORO,
PROP_MASTER.BLOCK,
PROP_MASTER.LOT,
PROP_MASTER.COL1,
PROP_MASTER.COL2,
PROP_MASTER.COL3,
COALESCE(TABLE2.COL4, 0) AS COL4,
COALESCE(TABLE3.COL5, 0) AS COL5
FROM PROP_MASTER
LEFT JOIN TABLE2 ON
TABLE2.BORO = PROP_MASTER.BORO
AND TABLE2.BLOCK = PROP_MASTER.BLOCK
AND TABLE2.LOT = PROP_MASTER.LOT
LEFT JOIN TABLE3 ON
TABLE3.BORO = PROP_MASTER.BORO
AND TABLE3.BLOCK = PROP_MASTER.BLOCK
AND TABLE3.LOT = PROP_MASTER.LOT
答案 1 :(得分:0)
参加工会
select col from PROP_MASTER
union
select col from TABLE2
union
select col from TABLE3
答案 2 :(得分:0)
您可以使用此
Select B.BORO,B.BLOCK,B.LOT,B.COL1,B.COL2,B.COL3,T2.COL4,T3.COL5
FROM PROP_MASTER B
LEFT join TABLE2 T2 ON B.BORO=T2.BORO AND B.BLOCK=T2.BLOCK AND B.LOT=T2.LOT
LEFT join TABLE3 T3 ON B.BORO=T3.BORO AND B.BLOCK=T3.BLOCK AND B.LOT=T3.LOT
WHERE
(T2.BORO IS NULL and T2.BLOCK IS NULL and T2.LOT IS NULL) OR
(T3.BORO IS NULL and T3.BLOCK IS NULL and T3.LOT IS NULL)