简体   繁体   English

在SQL左外部联接中,如何仅联接首次出现?

[英]In SQL left outer join, how to join first occurrence only?

Consider the following tables: 请考虑以下表格:

Table A 表A

Category  Misc
--------  ----
a         fsd
a         wer
b         fgg
c         ghj 
c         yui
c         rty

Table B (maps category to a number) 表B (将类别映射到数字)

Category  Num
--------  ---
a         1
b         2
c         3

Desired Outcome 期望的结果

Category  Num  Misc
--------  ---  ----
a         1    fsd
a              wer
b         2    fgg
c         3    ghj
c              yui
c              rty

A simple left outer join will try to map Num to every Category in Table A, but I only want Num to appear once. 一个简单的左外部联接将尝试将Num映射到表A中的每个类别,但是我只希望Num出现一次。 Can this be done? 能做到吗?

I'm still confused about the reason, but with your modification it is quite easily possible. 我仍然对原因感到困惑,但是通过您的修改很容易实现。 By left joining the same table grabbing any (the lowest in this case) Misc column, you can get a record for only one of the occurrences of each Cateogory in TableA. 通过左连接到同一张表以获取任何(在这种情况下,最低的)Misc列,您可以获得的记录仅是TableA中每个类别的一次出现。 Then you can left join TableB only on those rows where a record was found in that grouped subquery. 然后,您只能将联接TableB保留在该分组的子查询中找到记录的那些行上。

select
  a.Category,
  a.Misc,
  b.Num
from
  TableA a
  left join (
    select 
      Category, 
      min(Misc) as MinMisc 
    from 
      TableA
    group by
      Category) c on c.Category = a.Category and c.MinMisc = a.Misc
  left join TableB b on b.Category = a.Category and mc.Category is not null    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM