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

Trying to Use ORDER BY on a LEFT JOIN Query

我正在尝试使用左连接并连接 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

我想按索引 table 中的 MR_ID 对其进行排序,但每当我尝试向查询中添加 ORDER BY 时,它对我不起作用。有人可以帮我吗?

我想你在这之后

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, '')) 

积极先生先于我。由于您使用的是左连接,因此我还要为空值做准备。

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,'')
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;

以上是如果你想按你得到的最后一列排序。

如果你想在Index或Mastertable中按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;