sql联合使用不同的表达式

时间:2014-01-10 01:51:53

标签: sql sql-server

我有这个sql不起作用,因为两个联合会有不同的表达式,怎么办呢?谢谢(mssql存储过程)不知道从哪里开始

SELECT
*
FROM
(SELECT
    ROW_NUMBER()
        OVER 
            (ORDER BY T.TopicCreationDate desc)
        AS RowNumber
               ,T.TopicId, T.TopicTitle, T.TopicShortName, T.TopicDescription, T.TopicCreationDate, T.TopicViews, T.TopicReplies, T.UserId, T.TopicTags, T.TopicIsClose, 
                     T.TopicOrder, T.LastMessageId, T.UserName, M.MessageCreationDate, T.ReadAccessGroupId, T.PostAccessGroupId, U.UserGroupId, U.UserPhoto, T.UserFullName
    ,M.UserId AS MessageUserId
    ,MU.UserName AS MessageUserName
FROM            TopicsComplete AS T  LEFT OUTER JOIN
                     Messages AS M ON M.TopicId = T.TopicId AND M.MessageId = T.LastMessageId AND M.Active = 1  INNER JOIN
                     Users AS U ON U.UserId = T.UserId
    LEFT JOIN Users MU ON MU.UserId = M.UserId
        WHERE   EXISTS
    (  SELECT  *
      FROM    TopicsComplete
LEFT OUTER JOIN
                     Messages AS M ON M.TopicId = T.TopicId AND M.MessageId = T.LastMessageId AND M.Active = 1 INNER JOIN
                     Users AS U ON U.UserId = T.UserId LEFT OUTER JOIN
                     Users AS MU ON MU.UserId = M.UserId
WHERE        (T.UserId = @id)
          UNION
        SELECT  *
      FROM    TopicsComplete
            LEFT OUTER JOIN
                     Messages AS M ON M.TopicId = T.TopicId AND M.MessageId = T.LastMessageId AND M.Active = 1 INNER JOIN
                     topicfollows AS TF ON T.TopicId = TF.topicid INNER JOIN
                     Users AS U ON U.UserId = T.UserId LEFT JOIN 
                     Users MU ON MU.UserId = M.UserId
WHERE        (TF.userid = @id)
          )

) T

1 个答案:

答案 0 :(得分:1)

union的双方返回的所有列必须匹配(列数及其数据类型,而不是实际的名称/别名)。

首先,不要使用SELECT *指定返回的列。这是导致问题的坏习惯,例如当您向其中一个表添加新列时。

其次,如果联合的一部分没有足够的列,请指定一些常量来为这些列提供值(为了清晰起见添加别名),例如。

SELECT 0 AS RowNumber, T.TopicId, T.TopicTitle, T.TopicShortName, T.TopicDescription, T.TopicCreationDate, T.TopicViews, T.TopicReplies, T.UserId, T.TopicTags, T.TopicIsClose, 
                 T.TopicOrder, T.LastMessageId, T.UserName, M.MessageCreationDate, T.ReadAccessGroupId, T.PostAccessGroupId, U.UserGroupId, U.UserPhoto, T.UserFullName