简体   繁体   English

根据字段的值联接表

[英]joining of tables based on the value of the fields

I was struck with a problem in joining of tables, there is a condition regarding the joining of two tables.. I've three tables let us assume it table1,table2 & table3, 我在连接表时遇到了麻烦,有一个关于两个表的连接的条件。我有三个表,让我们假设它为table1,table2和table3,

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

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

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

Now, my master table is "table3", I need to join the master table with table1 & table2 in such a way that if the value of table2_id exists in the table3 then table2 should be joined with table2_id & similarly if table1_id exits then table1 will be joined with the table1_id,for eg: the entry into table3 is in this way 现在,我的主表是“ table3”,我需要以这样的方式将主表与table1和table2联接:如果table3中存在table2_id的值,那么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..

您可以尝试建立可放入条件并根据条件执行查询的过程。

You can probably do it using a LEFT JOIN and then sorting out the resulting columns required using a CASE statement. 您可能可以使用LEFT JOIN进行操作,然后使用CASE语句对所需的结果列进行排序。

As an example you could do something like this. 例如,您可以执行以下操作。 Note you would need to repeat the CASE statement for each field you want to bring back. 请注意,您需要为要返回的每个字段重复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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM