2013-04-10 91 views
0

我在加入表格時遇到了問題,有關於加入兩個表格的條件.. 我有三個表讓我們假設它是表1,表2 &表3,根據字段的值加入表格

table1 
+---+ 
|id | 
+---+ 

table2 
+---------------+ 
|id | table1_id | 
+---------------+ 

table3 
+----------------------------+ 
| id | table1_id | table2_id | 
+----------------------------+ 

現在,我的主表「表3」,我需要用表1 &表2加入主表以這樣一種方式,如果table2_id的值在表3存在,那麼表2,應與加盟table2_id &類似地,如果table1_id退出,那麼table1將與table1_id連接,例如:進入table3的條目是這樣的

+----------------------------+ 
| id | table1_id | table2_id | 
| 1 |  1  |  0  | 
| 2 |  0  |  1  | 
+----------------------------+ 

for the value of id = 1, 
table1_id exists & table2_id is zero, so table1 should be joined, 
for the id = 2, 
table2_id exists & table1_id is zero, so table2 should be joined, 
if there is a case that both exists then table2 should be given the priority i.e, the table2 will be joined, can anyone make me out of this prb pls.. 
+0

我對加入哪個表有點困惑。你似乎在說,如果我們在table2和table3之間有一個匹配,然後將table1連接到table3,並且如果我們在table1和table3之間匹配,則將table2連接到table3。你可能會舉幾個例子? – Kickstart 2013-04-10 10:37:19

+0

嗨Kickstart我修改了我的問題..pls有一個luk – kumar 2013-04-10 10:46:07

回答

0

您可以嘗試製作過程,在該過程中可以根據條件放置條件並執行查詢。

0

您可以使用LEFT JOIN執行此操作,然後使用CASE語句對結果列進行整理。

作爲一個例子,你可以做這樣的事情。請注意,您需要爲每個要恢復的字段重複CASE語句。

SELECT table3.id, CASE table2.id IS NULL THEN table1.field ELSE table2.field END AS field 
FROM table3 
LEFT OUTER JOIN table2 ON table3.table2_id = table2.id 
LEFT OUTER JOIN table1 ON table3.table1_id = table1.id