sql—如何将查询转换为子查询以返回所有值

qhhrdooz  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(416)

我有以下查询,它给出了正确的结果,如下所示:

SELECT *
FROM dbo.QAA
INNER JOIN dbo.QA
ON QAA.ID = QA.ID
INNER JOIN dbo.Q
ON Q.QID = QA.QID
INNER JOIN dbo.V
ON V.VID = QAA.VID
Where
Q.QID = 1111
and V.SID = 4785
and V.VID = QAA.VID
and QA.TypeID = 4 and code <> '75785'

这给了我下表

Answer       | Code | User 
Apples       |45879 |958-dfdf255-sdfsdf
Banana       |45214 |958-dfdf255-sdfsdf
Carrot       |74896 |958-dfdf255-sdfsdf

正如你所看到的,我得到了上面3个不同的答案。现在我需要添加这个查询作为子查询,如下所示

SELECT Name 
         , FirstName 
,table.code
        (SELECT Top 1
                QAA.Answer
                FROM dbo.QAA
        INNER JOIN dbo.QA
        ON QAA.ID = QA.ID
        INNER JOIN dbo.Q
        ON Q.QID = QA.QID
        INNER JOIN dbo.V
        ON V.VID = QAA.VID
        Where
        Q.QID = 1111
        and V.SID = 4785
        and V.VID = QAA.VID
        and QA.TypeID = 4 and code <> '75785') AS AnswerComment 
    from table
    where table.code=5

但是现在我没有得到所有的答案,这就是table的样子

AnswerComment        | code | Name               | firstname
    Apples            |45879 |958-dfdf255-sdfsdf  | Jane
    Apples            |45214 |958-dfdf255-sdfsdf  |Jane
    Apples            |74896 |958-dfdf255-sdfsdf  |Jane

我的问题在子查询中,如何返回所有答案注解?
我知道top 1只会检索第一条记录,这只是一个示例。我也试过了

select max (QAA.Answer)

但这也只返回一个值

ngynwnxp

ngynwnxp1#

使用 join 如果你想输入名字的话。我猜join键在user列上:

SELECT ?.AnswerComment, ?.code, n.Name, n.firstname
FROM dbo.QAA INNER JOIN
     dbo.QA
     ON QAA.ID = QA.ID INNER JOIN
     dbo.Q
     ON Q.QID = QA.QID INNER JOIN
     dbo.V
     ON V.VID = QAA.VID JOIN
     names n -- your new table
     ON n.user = ?.user
WHERE Q.QID = 1111 AND
      V.SID = 4785 AND
      QA.TypeID = 4 AND
      ?.code <> '75785'

注意,我删除了这个条件 V.VID = QAA.VID 因为它是多余的。
这个 ? 用于表别名以正确限定列名。

相关问题