我缺乏SQL经验,需要将多层过滤器应用于多个表以进行比较。
表1:
Order_Number Step_Name数据Parameter_Name
12 step4 const1 P1
12 step4 const2 P2
12 step4 value1 P3
30 step6 const3 P1
30 step6 const4 P2
30 step6 value2 P3
所有表格格式相同,数据值不同。 订单号可能因表而异。
我想这样做:
Order_Number表数据Parameter_Name
12 table1 value1 P3
12 table2 value2 P3
14 table3 value3 P3
非常感谢您的帮助!
答案 0 :(得分:0)
您需要根据需要添加尽可能多的union all...select
部分:
select
order_number,
'table1' as `table`,
data,
prameter_name
from
table1 t1p3
where
step_name in ('step1', 'step2', 'step3', 'step4', 'step5', 'step6', 'step7', 'step8') and
parameter = 'p3' and
exists (
select
'x'
from
table1 t1p1
where
t1p1.order_number = t1p3.order_number and
t1p1.step_name = t1p3.step_name and
t1p1.parameter = 'p1' and
t1p1.data = 'const1'
) and exists (
select
'x'
from
table1 t1p2
where
t1p2.order_number = t1p3.order_number and
t1p2.step_name = t1p3.step_name and
t1p2.parameter = 'p2' and
t1p2.data = 'const2'
)
union all
select
order_number,
'table2',
data,
prameter_name
from
table2 t2p3
where
step_name in ('step1', 'step2', 'step3', 'step4', 'step5', 'step6', 'step7', 'step8') and
parameter = 'p3' and
exists (
select
'x'
from
table2 t2p1
where
t2p1.order_number = t2p3.order_number and
t2p1.step_name = t2p3.step_name and
t2p1.parameter = 'p1' and
t2p1.data = 'const1'
) and exists (
select
'x'
from
table2 t2p2
where
t2p2.order_number = t2p3.order_number and
t2p2.step_name = t2p3.step_name and
t2p2.parameter = 'p2' and
t2p2.data = 'const2'
)