如何在2个以上的表Sql Server之间创建一个联合

时间:2012-09-11 14:29:10

标签: sql-server tsql

  

可能重复:
  How to Join three tables

我有4张桌子:

  • 文件夹(id_folder,name)
  • 子文件夹(id_subfolder,id_folder,名称,othercolumn,...)
  • 件(id_piece,id_subfolder,id_folder)
  • 图像(id_image,id_piece,名称,..)

如何获取一个文件夹的所有内容(例如“id_folder = 1”)?

2 个答案:

答案 0 :(得分:2)

假设这些表之间存在从零到多的关系,这样可以起作用:

SELECT folder.id_folder, folder.name, subfolder.id_subfolder, subfolder.name, subfolder.othercolumn, piece.id_piece, image.id_image, image.name
FROM folder
LEFT JOIN subfolder
ON folder.id_Folder = subfolder.id_folder
LEFT JOIN Piece
ON subfolder.id_subfolder = piece.id_subfolder
LEFT JOIN [image]
on piece.id_piece = image.id_piece
WHERE folder.id_folder = 1;

答案 1 :(得分:1)

你会JOIN你的表格,如下所示:

select *
from folder f
left join subfolder sf
    on f.id_folder = sf.id_folder
left join piece p
    on sf.id_subfolder = p.id_subfolder
    and sf.id_folder = p.id_folder
left join image i
    on p.id_piece = i.id_piece
where f.id_folder = 1

如果您需要帮助学习JOIN语法,那么有一个很棒的Visual Explanation of SQL Joins会有所帮助。