我有三个表,我想基于一个表的字段中的值以灵活的方式联接这三个表中的数据。
这是一个自我评估和管理评估系统。我在这里尝试过其他文章中的解决方案,但是由于我的数据结构与其他人不同,所以没有一个适合我。
表是这样的:
Tokens: SubmitterID, SubjectID, Origin, Token
Submitters: ID, FullName, Email
Subjects: ID, FullName, Email
在“令牌”表中:
我需要一个查询来为我提供以下内容:
提交者和主题的全名,提交者的电子邮件和令牌。到目前为止,我没有任何实际输出,因为我无法编写此查询。
答案 0 :(得分:2)
在这种情况下,您将表与所有可能的选项(“提交者”和“主题”)联接在一起,然后根据源值使用条件(CASE)返回所需的值。
SELECT T.Token,
CASE Origin
WHEN 1 THEN SM_Submitter.Fullname
WHEN 2 THEN SJ_Submitter.Fullname
WHEN 3 THEN SM_Submitter.Fullname
END AS SubmitterFullName,
CASE Origin
WHEN 1 THEN SM_Subject.Fullname
WHEN 2 THEN SJ_Subject.Fullname
WHEN 3 THEN SJ_Subject.Fullname
END AS SubjectFullName,
CASE Origin
WHEN 1 THEN SM_Submitter.Email
WHEN 2 THEN SJ_Submitter.Email
WHEN 3 THEN SM_Submitter.Email
END AS SubmitterEmail
FROM dbo.Tokens AS T
LEFT OUTER JOIN dbo.Submitters AS SM_Submitter ON SM_Submitter.ID = T.SubmitterID
LEFT OUTER JOIN dbo.Submitters AS SM_Subject ON SM_Subject.ID = T.SubjectID
LEFT OUTER JOIN dbo.Subjects AS SJ_Submitter ON SJ_Submitter.ID = T.SubmitterID
LEFT OUTER JOIN dbo.Subjects AS SJ_Subject ON SJ_Subject.ID = T.SubjectID
答案 1 :(得分:-1)
SELECT * FROM令牌令牌 JOIN提交者提交ON token.SubmitterId = Submit.ID JOIN主题subj ON令牌。SubjectID= subj.ID
您可以尝试查询吗?