繁体   English   中英

与一个不同的列合并

[英]Union with one different column

我想使用UNION连接两个视图(视图CSP多包含1列,因此如果第二个视图中的某些项不在第一个视图中,则我想在第二个中使用*),但效果很好,但是我没有重复的配置ID要么带有正确的值,要么带有*。

当csp中有值时,如何解决该问题并删除带有“ *”的行?

SELECT csp.customer_no,
       csp.contract,
       csp.customer_part_no,
       csp.configuration_id,
       csp.catalog_no
FROM customersomething csp
UNION
SELECT spc.customer_no,
       spc.contract,
       spc.customer_part_no,
       '*' AS "configuration_id",
       spc.catalog_no
FROM
superproduct spc

+-------------+----------+-----+------------------+--------+
| customer_no | contract | ... | configuration_id |        |
+-------------+----------+-----+------------------+--------+
|          17 | whatever | ... | *                | view A |
|          17 | whatever | ... | right_one        | view B |
+-------------+----------+-----+------------------+--------+

首先,使用union all除非您要承担删除重复项的开销。

第二,滤除第二个。 这是使用not exists

SELECT csp.customer_no, csp.contract, csp.customer_part_no,
       csp.configuration_id, csp.catalog_no
FROM customersomething csp
UNION ALL
SELECT spc.customer_no, spc.contract, spc.customer_part_no,
       '*' AS "configuration_id", spc.catalog_no
FROM superproduct spc
WHERE NOT EXISTS (SELECT 1
                  FROM customersomething csp
                  WHERE scp.customer_no = spc.customer_no
                 );

您可以使用此查询,

SELECT spc.customer_no,
   spc.contract,
   spc.customer_part_no,
   csp.configuration_id,
   spc.catalog_no FROM superproduct spc
   LEFT JOIN customersomething csp ON spc.customer_no = csp.customer_no
   UNION ALL
   SELECT csp.customer_no,
   csp.contract,
   csp.customer_part_no,
   csp.configuration_id,
   csp.catalog_no
   FROM customersomething csp
   LEFT JOIN  superproduct spc ON spc.customer_no = csp.customer_no AND spc.customer_no IS NULL

暂无
暂无

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

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