有没有更简单的方法将父数据左连接到多个子左连接数据?
表结构:
Table1 {id, name, data1, data2, datax}
Table2 {id, table1_id, dataA, dataB, userid}
Table3 {id, table1_id, dataD, userid}
Table4 {id, table1_id, dataE, userid}
TableUsers {userid, username, name, email}
SQL查询:
select Table1.*, Table2.*,Table3.*,Table4.*
from Table1 t1
left outer join Table2 t2 on t2.table1_id = t1.id
left outer join Table3 t3 on t3.table1_id = t1.id
left outer join Table4 t4 on t4.table1_id = t1.id
从这里我想用实际的用户名替换 userid 字段,并且每个表都有不同的用户 ID 数据,因此使用 TableUsers 的简单左连接将不起作用,因为它只会影响它设置为等于的表。
我曾考虑过使用子查询来做这件事,但相信这会特别慢:
select Table1.*,(select TableUser.name from TableUser where Table1.userid = TableUser.userid) as T1Name,
Table2.*,(select TableUser.name from TableUser where Table2.userid = TableUser.userid) as T2Name,
Table3.*, (select TableUser.name from TableUser where Table3.userid = TableUser.userid) as T3Name,
Table4.*,(select TableUser.name from TableUser where Table1.userid = TableUser.userid) as T4Name
from Table1 t1
left outer join Table2 t2 on t2.table1_id = t1.id
left outer join Table3 t3 on t3.table1_id = t1.id
left outer join Table4 t4 on t4.table1_id = t1.id
这样做的目的是从 SQL 数据库迁移到 MongoDB。也许我需要重新考虑整个查询...干杯,
芯片