加入select语句时出现问题

时间:2011-07-11 06:53:46

标签: sql

SELECT COUNT( WiningComment) AS 'WinningAnswers'
FROM Threads
WHERE WiningComment IN (SELECT CommentsID
FROM Comments
WHERE  UsersID=@UserID)

UNION ALL
SELECT COUNT(CommentsID)  AS 'TotalAnswers'
FROM  Comments
WHERE  UsersID=@UserID

我希望TotalAnswers和WinningAnswers显示为两个单独的列。但是当我测试查询时,我得到一行有两个数字......

5 个答案:

答案 0 :(得分:2)

UNION运算符按定义连接两个结果集并组合它们的行 - 两个结果集=至少两行。

您正在寻找的东西就像一个SELECT,有两个子选择来获取这些值:

SELECT 
    (SELECT COUNT(WiningComment) 
     FROM dbo.Threads t
     INNER JOIN dbo.Comments c ON t.WiningComment = c.CommentsID
     WHERE UsersID = @UserID) AS 'WinningAnswers',

   (SELECT COUNT(CommentsID) 
    FROM  dbo.Comments
    WHERE  UsersID = @UserID) AS 'TotalAnswers'

答案 1 :(得分:1)

这就是UNION所做的......它创建了两个数据集的 union

(1,2,3) UNION (4,5,6) = (1,2,3,4,5,6)

你基本上有两个单独的查询,所以你应该只做两个单独的查询。

答案 2 :(得分:1)

SELECT (
    SELECT COUNT( WiningComment)
    FROM Threads
    WHERE WiningComment IN (SELECT CommentsID
    FROM Comments
    WHERE  UsersID=@UserID)
) as 'WinningAnswers',
(
    SELECT COUNT(CommentsID)
    FROM  Comments
    WHERE  UsersID=@UserID
) as 'TotalAnswers'

答案 3 :(得分:0)

如果使用union,则无法执行此操作,两个查询中的列名必须相同。尝试进行单一查询。

答案 4 :(得分:0)

例如,您可以进行一些分组:

SELECT MAX(WinningAnswers) AS 'WinningAnswers', MAX(TotalAnswers) AS 'TotalAnswers'
FROM (
    SELECT t.UsersID, COUNT(t.WiningComment) AS 'WinningAnswers', 0 AS 'TotalAnswers'
    FROM Threads t
      JOIN Comments c ON c.CommentsID = t.WiningComment
    WHERE t.UsersID = @UserID
    UNION ALL
    SELECT UsersID, 0 AS 'WinningAnswers', COUNT(CommentsID) AS 'TotalAnswers'
    FROM Comments
    WHERE UsersID = @UserID
  ) AS Total
GROUP BY UsersID;

或者,考虑到您的第二个查询只返回一条记录,您可以简单地:

SELECT COUNT(t.WiningComment) AS 'WinningAnswers', Total.TotalAnswers AS 'TotalAnswers'
FROM (
      SELECT COUNT(CommentsID) AS 'TotalAnswers'
      FROM Comments
      WHERE UsersID = @UserID
    ) AS Total, Threads t
  JOIN Comments c ON c.CommentsID = t.WiningComment
WHERE t.UsersID = @UserID;