SQL选择多个连接

时间:2017-09-11 07:21:37

标签: sql sql-server

我有一个包含三个表的数据库示例。

1 Work: workID, stateID, createddate

2 Work history table: workID, old_state, new_state, transitiondate

3 Work state: StateID; Statename

我们说可能的状态是1 = ready2 = test3 = approved

我想进行打印列表工作的查询以及所有状态更改。结果看起来应该是这样的:

ID, createddate, Currentstate, OldState, Newstate, transitiondate
1,  1-1-2016,    approved,     ready,    test,     1-1-2016
1,  1-1-2016,    approved,     test,     approved, 2-1-2016
2,  1-5-2016,    test,         ready,    test,     1-5-2016
3,  1-10-2016,   approved,     ready,    test,     1-10-2016
3,  1-10-2016,   approved,     test,     approved, 1-15-2016 
...

我知道如何进行内部连接,这样我就可以轻松地从状态表中获取当前工作状态的名称,但是我无法获得旧状态和新状态的名称。我应该使用哪种连接命令?

3 个答案:

答案 0 :(得分:0)

请使用以下查询 -

monotonically_increasing_id()

答案 1 :(得分:0)

使用3个内连接到同一个表 - 如下 -

select 
w.workID as ID, 
W.createddate, 
WSC.Statename as Currentstate, 
WSO.Statename as OldState , 
WSN.Statename as Newstate, 
WH.transitiondate
from Work W
inner join workHistory WH on w.workID = WH.workID
inner join WorkState WSC on WSC.StateId = W.StateId
inner join WorkState WSO on WHO.StateId = WH.OldState
inner join WorkState WSN on WSN.StateId = WH.Newstate

OR

select 
w.workID as ID, 
W.createddate, 
(select top 1 Statename from WorkState where stateId = W.StateId) as Currentstate, 
(select top 1 Statename from WorkState where stateId = WH.OldState) as OldState , 
(select top 1 Statename from WorkState where stateId = WH.Newstate) as Newstate, 
WH.transitiondate
from Work W
inner join workHistory WH on w.workID = WH.workID

答案 2 :(得分:0)

Hello Valtteri Vaahtonen,

你应该考虑使用[工作历史]表作为主表使用LEFT JOIN,然后将其他表链接到它:

SELECT WH.ID, W.createddate, WS.Statename AS Currentstate, WH.OldState, WH.Newstate, WH.transitiondate 
FROM [Work history] WH 
LEFT JOIN [Work] W on WH.workID = W.workID
INNER JOIN [Work state] WS ON WS.StateID = W.StateID

让我知道它是否有帮助!