Mysql 基于字段值的表联接
我突然想到了一个表格连接的问题,关于两个表格的连接有一个条件。。 我有三张表,假设是表1,表2和表3Mysql 基于字段值的表联接,mysql,Mysql,我突然想到了一个表格连接的问题,关于两个表格的连接有一个条件。。 我有三张表,假设是表1,表2和表3 table1 +---+ |id | +---+ table2 +---------------+ |id | table1_id | +---------------+ table3 +----------------------------+ | id | table1_id | table2_id | +----------------------------+ 现在,我的主表是“t
table1
+---+
|id |
+---+
table2
+---------------+
|id | table1_id |
+---------------+
table3
+----------------------------+
| id | table1_id | table2_id |
+----------------------------+
现在,我的主表是“table3”,我需要将主表与table1和table2连接起来,如果table2\u id的值存在于table3中,那么table2应该与table2\u id连接起来&同样,如果table1\u id存在,那么table1将与table1\u 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..
您可以尝试创建一个过程,在该过程中,您可以放置条件并根据您的条件执行查询。您可能可以使用左连接来完成此操作,然后使用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
我有点搞不清楚哪些表在哪里连接。您似乎在说,如果表2和表3之间存在匹配,则将表1连接到表3,如果表1和表3之间存在匹配,则将表2连接到表3。你能给我举几个例子吗?嗨,Kickstart,我修改了我的问题,请回答