小编典典

SQL LEFT JOIN仅第一行

sql

假设我们有这样的数据集:

表格:DataTable1

ID      ExperienceId   LanguageId    ...
-------------------------------------------
1       1              1
2       1              2
3       1              3
4       2              1
5       2              2
6       2              3
7       3              1
8       3              2
9       3              3
...

表格:DataTable2

ID      SomeId OtherId LanguageId    ...
-------------------------------------------
1       459    1       1
2       459    1       2
3       459    1       3
4       245    2       1
5       245    2       2
6       245    2       3
7       295    3       1
8       295    3       2
9       295    3       3
...

我想加入这些表,而只获得SomeId列,而忽略LanguageId列。为了使它更清楚:

SELECT
    t2.SomeId AS RequiredId
    -- ...other data mainly from t2
FROM DataTable1 AS t1
LEFT JOIN DataTable2 AS t2 
    ON t2.OtherId = t1.ExperienceId 
    AND t2.LanguageId = 
        (SELECT TOP 1 t1.LanguageId
         ORDER BY t1.LanguageId)

此查询应返回(如果没有错,很明显)行:

SomeId    ...
----------------
459       ...
245       ...
295       ...
...

现在,它返回三次相同的数据(只有LanguageId不同)。

WHERE t1.LanguageId = 1如果我确定它始终存在,我将尝试使用它进行过滤,但是我不确定。行可以是LanguageId1到3,也只能是ID
2,以此类推。行肯定会有至少一个LanguageId

现在我的问题是: 如何将具有唯一值且表中的一列完全忽略的表联接起来


阅读 403

收藏
2021-05-23

共1个答案

小编典典

将其包装在另一个查询中有窍门吗?

SELECT RequiredId, <all_the_other_fields> from (
SELECT t2.SomeId AS RequiredId
-- ...other data mainly from t2
FROM DataTable1 AS t1
   LEFT JOIN DataTable2 AS t2 
   ON t2.OtherId = t1.ExperienceId 
   AND t2.LanguageId = 
      (SELECT TOP 1 t1.LanguageId
      ORDER BY t1.LanguageId)
   ) group by RequiredId, <all_the_other_fields>

甚至根本不提取列?

SELECT distinct t2.SomeId AS RequiredId
-- ...other data mainly from t2 BUT not the Language id
FROM DataTable1 AS t1
   LEFT JOIN DataTable2 AS t2 
   ON t2.OtherId = t1.ExperienceId 
   AND t2.LanguageId = 
      (SELECT TOP 1 t1.LanguageId
      ORDER BY t1.LanguageId)
2021-05-23