假设我有一个包含以下表格的数据库:
现在我想创建一个数据结构(可能是单个表,但如果有这样的需要,也可能有几个表),其中包含不同类型的项目列表:文件,文件夹和鲜花。我也希望这个列表保持数据的一致性(外键等)。
有可能吗?如果是这样,怎么办呢?
如果需要,可以修改原始表格。假设数据库是MS SQL Server。
答案 0 :(得分:1)
你可能只想要一个View
,它本质上是一个保存的查询。这样,当基础表发生变化时,您会看到更改
e.g。
CREATE VIEW MyStuff AS
SELECT 'Flower' AS [Type], [Name], NULL AS [Parent]
--Flowers don't have a parent folder
FROM [Flower]
UNION ALL
SELECT 'File' AS [Type], [File].[Name], [Folder].[Name] AS [Parent]
FROM [File]
JOIN [Folder] ON [File].[FolderID] = [Folder].[ID]
--Join on your foreign key
UNION ALL
SELECT 'Folder' AS [Type], [Folder].[Name], [ParentFolder].[Name] AS [Parent]
--I am assuming folders have a parent (apart from the root)
FROM [Folder]
LEFT JOIN [Folder] AS ParentFolder ON [Folder].[ParentID] = [ParentFolder].[ID]
--Left Join so that the root is also displayed