我有一个名为Entity
的表,该表仅包含一个ID int
作为主键。我也有许多任务表(Task1, Task2, Task3,
...)。这些任务表有许多单独的列,但共有三列:
time_created datetime2(7)
列,默认设置为getdate()
ID int
PKID_Entity
(当然是实体表的PK)。CREATE TABLE [dbo].[Task1]
(
[ID_Task1] [int] IDENTITY(1,1) NOT NULL,
[describer] [nvarchar](30) NOT NULL,
[ID_Entity] [int] NOT NULL,
[timestamp] [datetime2](7) NOT NULL,
[individual_task_value] [float] NOT NULL,
CONSTRAINT [PK_Task1]
PRIMARY KEY CLUSTERED ([ID_Task1] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Task1]
ADD CONSTRAINT [DF_Task1_timestamp] DEFAULT (GETDATE()) FOR [timestamp]
GO
ALTER TABLE [dbo].[Task1] WITH CHECK
ADD CONSTRAINT [FK_Task1_Entity]
FOREIGN KEY([ID_Entity]) REFERENCES [dbo].[Entity] ([id])
GO
ALTER TABLE [dbo].[Task1] CHECK CONSTRAINT [FK_Task1_Entity]
GO
因此,基本上一个实体可以具有多个不同类型的任务。
创建一个连接所有这些表的查询是否可行,从而为一个实体提供不同的任务(按日期时间排序)?
说我要查询ID为1的实体,并获取分配给它的所有任务的列表:
+-----------+------------------+-------+---------+
| ID_ENTITY | DATETIME | TASK | TASK_ID |
+-----------+------------------+-------+---------+
| 1 | 2020.03.01 17:30 | task1 | 1 |
| 1 | 2020.03.01 17:40 | task2 | 1 |
| 1 | 2020.03.02 06:30 | task1 | 2 |
| 1 | 2020.03.02 06:31 | task3 | 1 |
| 1 | 2020.03.02 06:32 | task2 | 2 |
| 1 | 2020.03.02 08:32 | task2 | 3 |
+-----------+------------------+-------+---------+
((ID_ENTITY
列没有意义,仅用于演示)
您对问题的描述在我看来像UNION
。>>
SELECT ID_Entity, [timestamp], 'Task1' AS Task, [ID_Task1] AS TaskID
FROM Task1
WHERE ID_Entity = 1
UNION ALL
SELECT ID_Entity, [timestamp], 'Task2' AS Task, [ID_Task2] AS TaskID
FROM Task2
WHERE ID_Entity = 1
UNION ALL
SELECT ID_Entity, [timestamp], 'Task3' AS Task, [ID_Task3] AS TaskID
FROM Task3
WHERE ID_Entity = 1
UNION ALL
...
ORDER BY [timestamp];
简单的UNION ALL
将完成工作:
您应该为此编写一个递归查询