我对连接表格感到震惊,有两个表加入的条件。 我有三张桌子让我们假设它是table1,table2&表3,
table1
+---+
|id |
+---+
table2
+---------------+
|id | table1_id |
+---------------+
table3
+----------------------------+
| id | table1_id | table2_id |
+----------------------------+
现在,我的主表是“table3”,我需要使用table1&加入主表。 table2以这样的方式,如果table2_id的值存在于table3中,那么table2应该与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 :(得分:0)
您可以尝试制定程序,在该程序中您可以根据自己的条件设置条件并执行查询。
答案 1 :(得分: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