尝试在LEFT JOIN查询上使用ORDER BY

时间:2016-12-13 18:24:46

标签: sql-server group-by left-join sql-order-by

我正在尝试使用左连接并连接2个列名,以便它们一起显示在下拉列表中。这是我目前的询问。

SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', Master.MR_Name) AS MR_ID
FROM Index
LEFT JOIN Master
ON Master.MR_ID=Index.MR_ID

我想通过索引表中的MR_ID对它进行排序,但每当我尝试向查询添加ORDER BY时,它都不适用于我。有人可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

WITH cte AS (
SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', Master.MR_Name) AS MR_ID
FROM [Index]
LEFT JOIN Master
ON Master.MR_ID=Index.MR_ID
)
SELECT *
FROM
    cte
ORDER BY
    MR_ID;

以上是您想要按最后一栏订购。

如果要按索引或主表中的MR_ID进行排序,则无法进行排序,因为您使用的是DISTINCT运算符,这意味着它不是由最终查询决定的。在这种情况下,您需要以下

WITH cte AS (
SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', Master.MR_Name) AS MR_ID
    , Index.MR_ID AS sort_column
FROM [Index]
LEFT JOIN Master
ON Master.MR_ID=Index.MR_ID
)
SELECT MR_ID
FROM
    cte
ORDER BY
    sort_column;

答案 1 :(得分:1)

我认为你在此之后

SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', IsNull(Master.MR_Name, '')) AS MR_ID
FROM SIndex
LEFT JOIN Master ON Master.MR_ID=SIndex.MR_ID
Order by CONCAT(CAST(Index.MR_ID AS INT),' - ', IsNull(Master.MR_Name, '')) 

答案 2 :(得分:1)

先生先生打败了我。我也准备空值,因为你正在使用左连接。

select distinct concat(cast(index.mr_id as int),' - ', isnull(master.mr_name,'') as mr_id
  from sindex
    left join master on master.mr_id=index.mr_id
  order by concat(cast(index.mr_id as int),' - ', isnull(master.mr_name,'')