如果两个表中的任何一个满足条件,则MySQL JOIN

时间:2017-07-27 07:27:42

标签: mysql sql join

SELECT COALESCE(table2.value, table3.value) FROM table1
JOIN table2 ON (table1.value = table2.value)
JOIN table3 ON (table1.value = table3.value)

table1.value = table2.valuetable1.value = table3.value是互斥的(最多其中一个是真的)。​​

如果table1.value = table2.valuetable1.value = table3.value为真,我如何才能进行加入?

这是唯一的解决方案吗? (这很乏味)

SELECT table.value FROM table1
JOIN 
(SELECT COALESCE(table2.value, table3.value) FROM table1
 LEFT JOIN table2 ON (table1.value = table2.value)
 LEFT JOIN table3 ON (table1.value = table3.value)
) as table ON (table1.value = table.value)

2 个答案:

答案 0 :(得分:2)

您可以使用两个查询和UNION个查询,例如:

SELECT COALESCE(table1.value, table2.value) FROM table1
JOIN table2 ON (table1.value = table2.value)

UNION

SELECT COALESCE(table1.value, table3.value) FROM table1
JOIN table3 ON (table1.value = table3.value)

答案 1 :(得分:0)

尝试使用内连接和联合两个表

SELECT * FROM
(SELECT value, data FROM table1) as a
INNER JOIN
(SELECT value, data FROM table2) as b
ON b.value = a.value
UNION ALL
(SELECT value, data FROM table1) as a
INNER JOIN
(SELECT value, data FROM table3) as b
ON b.value = a.value

内部JOIN将避免连接两个为NULL的表,它只会加入那些在两个表上都有完全查找的行。在UNION中我们假设在第一个JOIN中,另一个table3将不会被包含在那里,所以将它作为单独的连接和UNION它或将它合并到第一个,这样你就可以在一个查询/表上获得所有数据只要记住使用UNION,所有结果都应该具有您想要获取的确切名称或字段。