在2个别名sql server中使用相同的值

时间:2015-09-21 12:36:41

标签: sql-server

我有这样的查询。

SELECT
  ( SELECT StatusName
   FROM dbo.LMS_MST_Status
   WHERE MainStatusId = a.ParentID ) +'-'+ StatusName AS Value,

  ( SELECT StatusName
   FROM dbo.LMS_MST_Status
   WHERE MainStatusId = a.ParentID ) +'-'+ StatusName AS [Text]
FROM dbo.LMS_MST_Status a
WHERE ParentID > 0
  AND MainStatusID IS NOT NULL
ORDER BY [Text]

我有两个别名,即值和文本,但两者的值相同。这些列在前端处理,因此我无法更改前端代码。我甚至不能改变别名。所以我已经像上面那样提出了这个问题。但我觉得它会影响我的应用程序的性能,因为我使用两个别名的子查询。可以优化吗?

2 个答案:

答案 0 :(得分:1)

尝试left join

select
    b.StatusName +'-'+ a.StatusName AS [Value],
    b.StatusName +'-'+ a.StatusName AS [Text],
FROM dbo.LMS_MST_Status a
left join dbo.LMS_MST_Status b on a.ParentID = b.MainStatusId
WHERE ParentID > 0
AND MainStatusID IS NOT NULL
ORDER BY [Text]

您也可以尝试使用inner join(由@Damien_The_Unbeliever建议):

select
    b.StatusName +'-'+ a.StatusName AS [Value],
    b.StatusName +'-'+ a.StatusName AS [Text],
FROM dbo.LMS_MST_Status a
inner join dbo.LMS_MST_Status b on a.ParentID = b.MainStatusId
WHERE ParentID > 0
AND MainStatusID IS NOT NULL
ORDER BY [Text]

如果null条件满足,则不会创建任何a.ParentID = b.MainStatusId值,只会获取数据。

答案 1 :(得分:0)

您也可以使用APPLY(CROSS or OUTER)

SELECT  ca.StatusName AS Value ,
        ca.StatusName AS [Text]
FROM    dbo.LMS_MST_Status a
        CROSS APPLY ( SELECT    StatusName + '-' + a.StatusName AS StatusName
                      FROM      dbo.LMS_MST_Status
                      WHERE     MainStatusId = a.ParentID
                    ) ca
WHERE   ParentID > 0
        AND MainStatusID IS NOT NULL
ORDER BY [Text]