繁体   English   中英

根据字段的值联接表

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

我在连接表时遇到了麻烦,有一个关于两个表的连接的条件。我有三个表,让我们假设它为table1,table2和table3,

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

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

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

现在,我的主表是“ 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..

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

您可能可以使用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

暂无
暂无

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

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