简体   繁体   English

SQL不同的列和空值

[英]SQL Distinct Columns and Nulls

I'm trying to left outer join on 3 fields in 3 SQL tables. 我试图在3个SQL表中的3个字段上保留外部联接。 The goal is, given a query for object (O1) in table T1 with 3 elements (E1, E2, E3) in table T2 and 2 secondary features (S1, S2) in table T3, return a result set that looks like: 目标是,给定查询表T1中的对象(O1),并在表T2中具有3个元素(E1,E2,E3),在表T3中具有2个辅助特征(S1,S2),则返回如下结果集:

 O1 | E1 | S1
 O1 | E2 | S2
 O1 | E3 |

How would I go about doing this for multiple objects? 我将如何对多个对象执行此操作? I've tried left outer joins, group by, and a combination of different SQL queries but can't seem to return the rows in a way that isn't too many combinations.S 我尝试了左外部联接,分组依据以及不同SQL查询的组合,但似乎无法以太多组合的方式返回行。

Here is the simplest example I have tried which returns 6 results: 这是我尝试过的最简单的示例,它返回6个结果:

select aO, bE, cS from T1 a left outer join T2 b on aO = bO left outer join T3 c on aO = cO where aO in ('O1');

Results returned would be: 返回的结果将是:

O1 | E1 | S1 O1 | E1 | S2 O1 | E2 | S1 O1 | E2 | S2 O1 | E3 | S1 O1 | E3 | S2

Note: left outer join is used because I need the table to return results even if T2 or T3 do not have results. 注意:之所以使用左外部联接,是因为即使T2或T3没有结果,我也需要表返回结果。

I think what you want to do is treat T2 and T3 like they have a ordering and then join the orders together. 我认为您想要做的是像对待T2和T3一样下订单,然后将订单合并在一起。 You can do that like this: 您可以这样做:

select a.O, b.E, c.S
from T1 a 
left outer join (
  SELECT T2.*, ROW_NUMBER() OVER () as rn
  FROM T2     
) b on a.O = b.O 
left outer join (
  SELECT T3.*, ROW_NUMBER() OVER () as rn
  FROM T3 
) c on a.O = c.O and b.rn = c.rn
where a.O in ('O1');

This won't work if T3 has more "elements" than T2. 如果T3的“元素”比T2多,则此方法将无效。

If you want to do this for multiple objects in a then just add the following 如果您要对中的多个对象执行此操作,则只需添加以下内容

select a.O, b.E, c.S
from T1 a 
left outer join (
  SELECT T2.*, ROW_NUMBER() OVER (PARTITION BY O) as rn
  FROM T2     
) b on a.O = b.O 
left outer join (
  SELECT T3.*, ROW_NUMBER() OVER (PARTITION BY O) as rn
  FROM T3 
) c on a.O = c.O and b.rn = c.rn
where a.O in ('O1');

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

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