sql server多表检索
项目中共用到若干个表mainTable,table1,table2,table3...,主表mainTable包含ID,table1-ID,table2-ID,table3-ID,table1包含两个字段table1-ID,table1-name,table2,table3表结构和table1类似。
mainTable中table1-ID,table2-ID,table3-ID其中的一项或者两项可能为空,现在要查询mainTable,要求查询的结果如下:
ID table1-name table2-name table3-name
请问如何实现,请各位高手指点
------解决方案--------------------select ID, table1.table1-name, table2.table2-name, table3.table3-name
from mainTable
left outer join table1 on table1.id on mainTable.table1ID
left outer join table2 on table2.id on mainTable.table2ID
left outer join table3 on table3.id on mainTable.table3ID
------解决方案--------------------SELECT
a.iID,
[table1-name] = ISNULL(t1.NAME,''),
[table2-name] = ISNULL(t2.NAME,''),
[table3-name] = ISNULL(t3.NAME,'')
FROM mainTable a
LEFT JOIN table1 t1
ON a.table1_id = t1.id
LEFT JOIN table2 t2
ON a.table12_id = t2.id
LEFT JOIN table13 t3
ON a.table3_id = t3.id