我有四张桌子就像这样
---user table---|--Form table-----|---Request status-- |--Request Table--
UserId Username |FormId FormTitle |RequestId StatusId |RequestId Title UserId FormId
1 Test | 1 Form1 | 1 1 | 1 Request1 1 1
2 User | 2 Form2 | 2 1 | 2 Request2 1 1
我想从这张表中拉出记录
RequestId FormTitle UserName Status
1 Test 1 1
但目前我正在获得以下查询的多条记录
select r.RequestId,f.FormTitle,u.UserId, rs.StatusId from request r
Join requeststatus rs on rs.StatusId=rs.StatusId
left join [user] u on u.UserId=u.UserId
left join form f on f.FormId=f.FormId
where r.RequestId=1
我应该使用哪个联接来实现此目的?
答案 0 :(得分:3)
这毫无意义:
Join requeststatus rs on rs.StatusId = rs.StatusId
你想要
Join requeststatus rs on r.RequestId = rs.RequestId
与其他联接相同
所以这应该有效:
select r.RequestId,f.FormTitle,u.UserId, rs.StatusId
from request r
left join requeststatus rs on r.RequestId = rs.RequestId
left join [user] u on r.UserId = u.UserId
left join form f on r.FormId = f.FormId
where r.RequestId = 1
答案 1 :(得分:1)
你的JOIN条件中只有一点错字。 尝试格式化您的陈述。稍后将更容易支持和分析它们。
在您的情况下,请尝试:
SELECT r.RequestId
,f.FormTitle
,u.UserId
,rs.StatusId
FROM request r
LEFT OUTER JOIN requeststatus rs
ON rs.RequestId = r.RequestId
LEFT OUTER JOIN user u
ON u.UserId = r.UserId
LEFT OUTER JOIN form f
ON f.FormId = r.FormId
WHERE r.RequestId = 1
如果您愿意,JOINS
您的工作将无法胜任:
u.UserId=u.UserId
当您加入同一张表中的列时,#u
"
答案 2 :(得分:1)
尝试此查询。我认为你的问题是你并没有真正将一张桌子加入另一张桌子。您正在将相同的表连接到自身:
SELECT r.RequestId
,f.FormTitle
,u.UserId
,rs.StatusId
FROM request r
JOIN requeststatus rs ON rs.RequestID = r.RequestID
LEFT JOIN [user] u ON u.UserId = r.UserId
LEFT JOIN form f ON f.FormId = r.FormId
WHERE r.RequestId = 1
答案 3 :(得分:0)
我无法理解为什么每个人都在使用左连接。内部联接也起作用,并且在可能的情况下恕我直言。所以:
SELECT r.RequestId, f.FormTitle, u.UserId, rs.StatusId
FROM request r
INNER JOIN requeststatus rs
ON rs.requestid = r.requestid
INNER JOIN [user] u
ON u.UserId = r.UserId
INNER JOIN form f
ON f.FormId = r.FormId
WHERE r.RequestId = 1