我想从一个表中选择两个字段。
SELECT Book.Id,
Book.fristTitle,
Book.secondTitle,
Person.fName +' ' + Person.lName as author,
(Person.fName +' ' + Person.lName) as translator,
Subject.subjectTitle,
isbn,
editionNumber,
state,
type
FROM Book
INNER JOIN Subject ON Book.subjectId=Subject.Id
INNER JOIN Person ON Book.authorId=Person.Id
where Person.isAuthor=1
INNER JOIN Person ON Book.authorId=Person.Id
where Person.isTranslator=1
第一个字段为(Person.fName +' ' + Person.lName)
作为作者,第二个字段为(Person.fName +' ' + Person.lName)
作为库数据库中的翻译者
答案 0 :(得分:0)
虽然我认为您可能仍然遗漏某些内容,但您的查询应该更像是这样:
SELECT Book.Id, Book.fristTitle,Book.secondTitle,
P1.fName +' ' + P1.lName as author,
P2.fName +' ' + P2.lName as translator,
Subject.subjectTitle,isbn,editionNumber,state,type
FROM Book
INNER JOIN Subject ON Book.subjectId=Subject.Id
INNER JOIN Person P1 ON Book.authorId=P1.Id AND P1.isAuthor=1
INNER JOIN Person P2 ON Book.authorId=P2.Id AND P2.isTranslator=1
通常使用这种方法,您的Book
表格会有2个字段 - 一个用于author
,另一个用于translator
...
顺便说一句 - 使用这种方法,您必须在Person
表格中有多个行,Id
(IsAuthor = 1
为1,isTranslator = 1
为1 )。如果是这种情况,我强烈建议您查看数据库规范化。
更好的方法是在authorid
表格上设置translatorid
字段和book
字段。
答案 1 :(得分:0)
这应该有效:
string query = SELECT Book.Id, Book.fristTitle, Book.secondTitle,
A.fName +' ' + A.lName as author,
(T.fName +' ' + T.lName) as translator,
Subject.subjectTitle, isbn, editionNumber, state, type
FROM Book
INNER JOIN Subject ON Book.subjectId=Subject.Id
INNER JOIN Person as A ON Book.authorId = A.Id and A.isAuthor=1
INNER JOIN Person as T ON Book.authorId = T.Id and T.isTranslator=1
您需要两次加入Person,但每次都使用别名来区分哪组数据。
您不能拥有两个WHERE
条款(我在复制代码时最初重复的错误),因此您使用AND
来控制联接。