Sql 查询以联接多个表
我有一个名为Sql 查询以联接多个表,sql,sql-server,sql-server-2017,Sql,Sql Server,Sql Server 2017,我有一个名为Entity的表,它只包含一个ID int作为主键。 我还有许多任务表(Task1、Task2、Task3、…)。这些任务表有许多单独的列,但共有三列: 一列time\u创建了datetime2(7),默认设置为getdate() 他们自己的ID intPK 外键ID\u Entity(当然是Entity表的主键) 因此,基本上一个实体可以有多个不同类型的任务 是否可以创建一个连接所有这些表的查询,从而为一个实体提供不同的任务(按日期和时间排序) 假设我查询ID为1的实体,并获得分配
Entity
的表,它只包含一个ID int
作为主键。
我还有许多任务表(Task1、Task2、Task3、
…)。这些任务表有许多单独的列,但共有三列:
time\u创建了datetime2(7)
,默认设置为getdate()
ID int
PKID\u Entity
(当然是Entity表的主键)+-----------+------------------+-------+---------+
| 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\u 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];
你对问题的描述在我看来像是工会
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
就可以完成这项工作:
select *
from (
select [ID_Entity], [timestamp], describer, [ID_Task1] as task_id
from [dbo].[Task1] where [ID_Entity] = 123
union all
select [ID_Entity], [timestamp], describer, [ID_Task2]
from [dbo].[Task2] where [ID_Entity] = 123
union all
select [ID_Entity], [timestamp], describer, [ID_Task3]
from [dbo].[Task3] where [ID_Entity] = 123
) x
order by timestamp
一个简单的
UNION ALL
就可以完成这项工作:
select *
from (
select [ID_Entity], [timestamp], describer, [ID_Task1] as task_id
from [dbo].[Task1] where [ID_Entity] = 123
union all
select [ID_Entity], [timestamp], describer, [ID_Task2]
from [dbo].[Task2] where [ID_Entity] = 123
union all
select [ID_Entity], [timestamp], describer, [ID_Task3]
from [dbo].[Task3] where [ID_Entity] = 123
) x
order by timestamp
您应该为此编写递归查询您应该为此编写递归查询谢谢!那正是我要找的!以前从未使用过工会。谢谢!那正是我要找的!以前从未使用过工会。谢谢!那正是我要找的!以前从未使用过工会。谢谢!那正是我要找的!以前从未使用过联合。如果您使用的是
Datetime2(7)
数据类型(这是推荐且良好的做法),您还应该停止使用GETDATE()
函数(该函数仅返回Datetime
,精度为3.33毫秒),而改用SYSDATETIME()
(返回Datetime2(7)
)如果您使用的是Datetime2(7)
数据类型(这是推荐的和良好的做法),您还应该停止使用GETDATE()
函数(该函数只返回Datetime
,精度为3.33毫秒),而改用SYSDATETIME()
(返回Datetime2(7)
)