根据字段的值加入表格
问题描述:
我在加入表格时遇到了问题,有关于加入两个表格的条件.. 我有三个表让我们假设它是表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..
答
您可以尝试制作过程,在该过程中可以根据条件放置条件并执行查询。
答
您可以使用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
我对加入哪个表有点困惑。你似乎在说,如果我们在table2和table3之间有一个匹配,然后将table1连接到table3,并且如果我们在table1和table3之间匹配,则将table2连接到table3。你可能会举几个例子? – Kickstart 2013-04-10 10:37:19
嗨Kickstart我修改了我的问题..pls有一个luk – kumar 2013-04-10 10:46:07