删除 SQL 中的 NULL 值 SQL 中的 JOIN 和 UNION 运算符

Removing NULL value in SQL JOIN and UNION Operators in SQL

[已解决] 如何仅在字段 provider_order 中删除 NULL 值,在我的例子中 table 使用 JOIN Table 和联合

这是我的数据库架构和我的 SQL 查询

http://sqlfiddle.com/#!9/f77862/2

这里为了描述清楚我附上图片

The red line circle is which should be removed

删除是什么意思?删除整行或仅在 provider_order 中显示 NULL 以外的其他内容。如果以后要找,那么可以用COALESCE

编辑:仅在您的 fiddle 中进行了更改:http://sqlfiddle.com/#!9/f77862/46

您不能只删除一行中的那个字段。但是,您可以简单地通过使用 WHERE 子句过滤掉具有空值的记录来删除整行。

http://sqlfiddle.com/#!9/f77862/42

SELECT
    m.provider_id,
    m.provider_name,
    p.purchase_order_code,
    NULL AS purchase_order_sample_code,
    p.provider_id AS provider_order
FROM mst_provider AS m
LEFT JOIN trx_purchase_order AS p
    ON (m.provider_id = p.provider_id)
WHERE p.provider_id != NULL
UNION
SELECT
    m.provider_id,
    m.provider_name,
    p.purchase_order_code,
    NULL AS purchase_order_sample_code,
    p.provider_id AS provider_order
FROM mst_provider AS m
RIGHT JOIN trx_purchase_order AS p
    ON (m.provider_id = p.provider_id)
UNION
SELECT
    m.provider_id,
    m.provider_name,
    NULL,
    s.purchase_order_sample_code,
    s.provider_id
FROM mst_provider AS m
RIGHT JOIN trx_purchase_order_sample AS s
    ON (s.provider_id = m.provider_id)

我假设您想过滤 provider_order 为空的地方?

我将您的整个查询包装为一个子查询,并在末尾放置了一个 where 子句,仅返回 provider_order 不为空的记录。

http://sqlfiddle.com/#!9/f77862/50/0

SELECT *
FROM (
    SELECT m.provider_id,
        m.provider_name,
        p.purchase_order_code,
        NULL AS purchase_order_sample_code,
        p.provider_id AS provider_order
    FROM mst_provider AS m
    LEFT JOIN trx_purchase_order AS p
        ON (m.provider_id = p.provider_id)

    UNION

    SELECT m.provider_id,
        m.provider_name,
        p.purchase_order_code,
        NULL AS purchase_order_sample_code,
        p.provider_id AS provider_order
    FROM mst_provider AS m
    RIGHT JOIN trx_purchase_order AS p
        ON (m.provider_id = p.provider_id)

    UNION

    SELECT m.provider_id,
        m.provider_name,
        NULL,
        s.purchase_order_sample_code,
        s.provider_id
    FROM mst_provider AS m
    RIGHT JOIN trx_purchase_order_sample AS s
        ON (s.provider_id = m.provider_id)
    ) _temp
WHERE provider_order IS NOT NULL