Mysql SQL查询:从多个表中获取数据,使用公共字段相互连接,但不保证任何表都有数据。
我希望通过公共字段连接多个表来获取数据,但没有表保证其中包含数据 下面的示例将消除混淆: 表aMysql SQL查询:从多个表中获取数据,使用公共字段相互连接,但不保证任何表都有数据。,mysql,sql,join,Mysql,Sql,Join,我希望通过公共字段连接多个表来获取数据,但没有表保证其中包含数据 下面的示例将消除混淆: 表a commonId aName 2 2AName 5 5AName 8 8AName 表B commonId bName 3 3BName 8 8BName 表C commonId cName
commonId aName
2 2AName
5 5AName
8 8AName
表B
commonId bName
3 3BName
8 8BName
表C
commonId cName
1 1CName
2 2CName
3 3CName
从上述可用数据中,我们需要以下方式的数据:
commonId, aName, bName, cName
1 NULL NULL 1CName
2 2AName NULL 2CName
3 NULL 3BName 3CName
5 5AName NULL NULL
8 8AName 8BName NULL
谢谢。您想要的是
完全外部连接,MySQL不支持。我建议使用union all
和group by
来解决这个问题:
select commonId,
max(aName) as aName, max(bName) as bName, max(cName) as cName)
from ((select commonId, aName, NULL as bName, NULL as cName
from tableA
) union all
(select commonId, NULL as aName, bName, NULL as cName
from tableB
) union all
(select commonId, NULL as aName, NULL as bName, cName
from tableC
)
) abc
group by CommonId;
这假定表中没有任何重复项。如果有可能,您需要解释在这种情况下的结果是什么样子。MAX将对所有数据类型正常工作,即string,int…?@murtaza.webdev。是的,你想做什么?