我有一个搜索,但有很多问题听起来相同,但略微没有涵盖我需要的内容。
我有以下设置:
数据库: Job1 ,表格: 文档
id | rev_desc_id | created_by_id | modified_by_id | checker_id | approver_id ---|-------------|---------------|----------------|------------|------------ 1 | 1 | 1 | 1 | 2 | 3
" rev_desc_id" 链接MySoftware.dbo.Revision_Description.id
" created_by_id"," modified_by_id"," checker_id"," approver_id" 链接MyCompany.dbo。 Person.id
数据库: MyCompany ,表格 人
id | first_name | last_name ---|------------|---------- 1 | Tom | DeLonge 2 | Mark | Hoppus 3 | Travis | Barker
数据库: MySoftware ,表格 Revision_Description
id | name ---|------------ 1 | Draft 2 | For Comment
我有以下SQL:
SELECT Document.*, Revision_Description.name AS 'Rev Description', CONCAT(Person.first_name, ' ', Person.last_name) AS 'Created By'
FROM Document
INNER JOIN MySoftware.dbo.Revision_Description
ON rev_desc_id=Revision_Description.id
INNER JOIN MyCompany.dbo.Person
ON created_by_id=Person.id
这一切都运行正常,但我现在正处于需要返回其他连接名称的位置" modified"," checker"和"批准者"。我不确定如何提供这些特定的列名称,例如" AS Created By"。
我还有一些其他列也需要加入其他表。
我对数据库设计很陌生,我并没有尽力正确地命名和链接它们,所以如果我对这一切完全错误,请道歉。
非常感谢任何帮助或建议。
提前谢谢。
答案 0 :(得分:0)
SELECT d.*, s.name 'Rev Description',
CONCAT(c.first_name, ' ', c.last_name) CreatedBy,
CONCAT(m.first_name, ' ', m.last_name) ModifiedBy,
CONCAT(k.first_name, ' ', k.last_name) CheckedBy,
CONCAT(a.first_name, ' ', a.last_name) ApprovedBy,
FROM Document d
JOIN MySoftware.dbo.Revision_Description s
ON s.id = d.rev_desc_id
left JOIN MyCompany.dbo.Person c
ON c.id = d.created_by_id
left JOIN MyCompany.dbo.Person m
ON m.id = d.modified_by_id
left JOIN MyCompany.dbo.Person k
ON k.id = d.checker_id
left JOIN MyCompany.dbo.Person a
ON a.id = d.approver_id
答案 1 :(得分:0)
对于查找表,我更喜欢使用LEFT JOIN,但你可以将Person表添加N次并使用别名,具体取决于Creator,Checker,......
SELECT
Document.*,
Revision_Description.name AS 'Rev Description',
CONCAT(C.first_name, ' ', C.last_name) AS 'Created By',
CONCAT(M.first_name, ' ', M.last_name) AS 'Modified By',
CONCAT(K.first_name, ' ', K.last_name) AS 'Checked By'
FROM Document
INNER JOIN MySoftware.dbo.Revision_Description
ON rev_desc_id=Revision_Description.id
LEFT JOIN MyCompany.dbo.Person as C
ON created_by_id=C.id
LEFT JOIN MyCompany.dbo.Person as M
ON modified_by_id=M.id
LEFT JOIN MyCompany.dbo.Person as K
ON checked_id=K.id