2014-08-27 124 views
0

我對SQL沒有經驗,需要將多層過濾器應用於多個表以進行比較。將多個過濾器應用於多個表的sql查詢

表1:

ORDER_NUMBER STEP_NAME數據PARAMETER_NAME
12步驟4 CONST1 P1
12步驟4 CONST2 P2
12步驟4 VALUE1 P3
30步驟6 const3 P1
30步驟6 const4 P2
30步驟6 VALUE2 P3

所有表格具有相同的格式,只有數據值不同。 訂單號可能會因各個表而有所不同。

我想做的事:與

  1. 搜索行STEP_NAME =步驟1和步驟8只
  2. 查找ORDER_NUMBER匹配(P1 = const1--它和P2 = CONST2)
  3. 保存P3行以相同的順序號組。
  4. 顯示中的所有行(每個表):

ORDER_NUMBER表數據PARAMETER_NAME
12 table1的值1 P3
12表2 VALUE2 P3
14表3值3 P3

您的幫助是大大不勝感激!

+0

你是什麼意思與「多層過濾器」? – Horaciux 2014-08-27 22:25:16

回答

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' 
    ) 
+0

非常感謝。我遵循了你的步驟,並以更小的規模成功找到order_number,P1和P2在特定的值。 – AnneZ 2014-08-29 20:06:57