从一个表中选择两个字段

时间:2015-12-02 22:23:25

标签: sql

我想从一个表中选择两个字段。

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)作为库数据库中的翻译者

2 个答案:

答案 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表格中有多个行,IdIsAuthor = 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来控制联接。