简体   繁体   English

根据列值,查询不同的表

[英]Depending on column value, query different tables

I have table A where each IDENTIFIER value is unique.我有表 A,其中每个 IDENTIFIER 值都是唯一的。 Depending on whether its CC or DC, I need to join it with different tables, for example if its "CC_" I need to map it to table B and if its "DC_" I need to map it to table C.根据它的 CC 还是 DC,我需要将它与不同的表连接,例如,如果它的“CC_”我需要 map 到表 B,如果它的“DC_”我需要 map 它到表 Z0D61F8370CAD1D412F70B841。

TABLE A:表A:

ID | IDENTIFIER
1  | CC_1234567
2  | DC_9494949

TABLE B:表 B:

ID| SOURCE.  |INSTRUMENT
7 | 1234567. | 545454

TABLE C:表 C:

ID  |  SOURCE  | INSTRUMENT
8   |. 9494949 |. 63636363

I want the result to look like this:我希望结果如下所示:

IDENTIFIER | INSTRUMENT
CC_1234567 | 545454
DC_9494949 | 63636363

First of all, how could I just get "1234567" from "CC_1234567" and second when writing a join query, I would get other columns in the final resulting table, such as B.INSTRUMENT, C.INSTRUMENT.首先,我如何才能从“CC_1234567”中获取“1234567”,其次在编写连接查询时,我会在最终结果表中获取其他列,例如 B.INSTRUMENT、C.INSTRUMENT。 Each IDENTIFIER in table A only maps to either table B OR table C.表 A 中的每个 IDENTIFIER 仅映射到表 B 或表 C。

Select A.IDENTIFIER, B.INSTRUMENT, C.INSTRUMENT 
from table.A 
inner join table.A on A.IDENTIFIER=B.INSTRUMENT AND A.IDENTIFIER=C.INSTRUMENT

You can left join twice, and then use coalesce() in the select clause:您可以left join两次,然后在select子句中使用coalesce()

select a.identifier, coalesce(b.instrument, c.instrument) instrument
from tablea
left join tableb b on a.identifier = concat('CC_', b.source)
left join tablec c on a.identifier = concat('DC_', c.source)

If there are matches in both tables, the above query gives priority to tableb .如果两个表中都有匹配项,则上述查询优先考虑tableb

If you want to exclude rows that have no match in either tables, then you can add the following where clause:如果要排除任一表中不匹配的行,则可以添加以下where子句:

where a.source is not null or b.source is not null

You can use UNION like the following:您可以像下面这样使用 UNION:

SELECT 
    A.IDENTIFIER,
    B.INSTRUMENT  
FROM
    A 
    INNER JOIN B 
        ON B.SOURCE = SUBSTR(A.IDENTIFIER, 4) 
WHERE A.IDENTIFIER LIKE 'CC_' 
UNION
SELECT 
    A.IDENTIFIER,
    C.INSTRUMENT 
FROM
    A 
    INNER JOIN C 
        ON C.SOURCE = SUBSTR(A.IDENTIFIER, 4) 
WHERE A.IDENTIFIER LIKE 'DC_' ;

Depending on "CC_" or "DC_", you join a different table and merge using UNION.根据“CC_”或“DC_”,您可以加入不同的表并使用 UNION 进行合并。

Try this: the right function combined with length should give you a handy way to strip these going forward.试试这个:正确的 function 结合长度应该给你一个方便的方法来去除这些。

SELECT 
   a.identifier,
   coalesce(b.instrument, c.instrument) AS instrument
FROM
     a LEFT JOIN b ON 
   right(a.identifier,length(a.identifier)-3) = b.source 
      LEFT JOIN c ON
   right(a.identifier,length(a.identifier)-3) = c.source;

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

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