与一个不同的列联合

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