SQL查询左外连接不能用另一个表中的相同数据替换两列

时间:2016-12-20 05:41:51

标签: sql sql-server

我有一个表数据,假设有3列,即KMK_NM,KMK_ID1,KMK_ID2

KY_KMKNAME

+--------+---------+---------+
| KMK_NM | KMK_ID1 | KMK_ID2 |
+--------+---------+---------+
|        |         |         |
+--------+---------+---------+

和另一个名为KMKNAME的表 这就像

+--------+----------+
| KMK_ID | KMK_NAME |
+--------+----------+
|        |          |
+--------+----------+

现在当我运行查询时,我需要KY_KMKNAME表的数据以及数据 如果kmk_id1KMKNAME.KMK_KMKNAME匹配,则KMKNAME.KMK_ID =KY_KMKNAME.KMK_ID1替换为KMK_ID 2 SELECT KY.KMK_NM ,KY_KMK_ID1 ,KY.KMK_ID2 ,KMK.KMK_NAME AS KMK_ID1_NAME ,KMK.KMK_NAME AS KMK_ID2_NAME FROM KY_KMKNAME AS KY LEFT OUTER JOIN KMKNAME AS KMK ON KY.KMK_ID1 = KMK.KMK_ID 中的数据应该替换为pls help

我尝试的查询只替换了一列kmk_id1

--logo

1 个答案:

答案 0 :(得分:0)

您可以使用不同的On Condition再次连接到同一个表,以获得第二个ID列的信息,如下所示

SELECT KY.KMK_NM
    ,KY_KMK_ID1
    ,KY.KMK_ID2
    ,KMK.KMK_NAME AS KMK_ID1_NAME
    ,KMK2.KMK_NAME AS KMK_ID2_NAME
FROM KY_KMKNAME AS KY
LEFT OUTER JOIN KMKNAME AS KMK ON KY.KMK_ID1 = KMK.KMK_ID
LEFT OUTER JOIN KMKNAME AS KMK2 ON KY.KMK_ID2 = KMK2.KMK_ID