MySQL 列为 NULL 的视图

MySQL views where a column is NULL

自从我尝试制作此 MySQL 视图后,我就开始头疼了,其中一列的结果值为 NULL。我需要一个像 0 这样的真实值。

我从表 1 中取出我的 ID 并在表 2 中进行比较,所以它不确定是否有一个带有该 ID 的数字,如果表 2 中没有数字,该值将变为 NULL,而我需要的是 0 .这是我的视图代码:

CREATE VIEW `instock` AS
SELECT 
    table1.name AS name,
    table1.supl AS supply,
    table2.num AS numbers,
    table1.maxnum AS maxnumbers
FROM
    (table1
    LEFT JOIN table2 ON ((table1.id = table2.id)))
ORDER BY table1.name

它是我有 NULL 值的列号

您可以使用 ifnull 函数:

SELECT 
  table1.name AS name,
  table1.supl AS supply,
  ifnull(table2.num,0) AS numbers,
  table1.maxnum AS maxnumbers
FROM
  (table1
  LEFT JOIN table2 ON ((table1.id = table2.id)))
ORDER BY table1.name

我不确定您在查询中的 left joinleft join 给出 全部 left table (table1) 包括那些没有另一个 table (table2) 的对应方。对于从右边 table 开始的这些不匹配的行,您将获得所有 table2 列的 NULL,包括 table2.num.

也许您正在寻找 inner join。这取决于您的数据以及您的 table2.num 是否为 NULLable。要仅用零替换 NULL,请使用 COALESCE

CREATE VIEW `instock` AS
SELECT 
    table1.name AS name,
    table1.supl AS supply,
    COALESCE(table2.num,0) AS numbers,
    table1.maxnum AS maxnumbers
FROM
    (table1
    LEFT JOIN table2 ON ((table1.id = table2.id)))
ORDER BY table1.name

IFNULL

CREATE VIEW `instock` AS
SELECT 
    table1.name AS name,
    table1.supl AS supply,
    IFNULL(table2.num,0) AS numbers,
    table1.maxnum AS maxnumbers
FROM
    (table1
    LEFT JOIN table2 ON ((table1.id = table2.id)))
ORDER BY table1.name

如果您想完全跳过 table2 中不在 table1 中的项目(wrt。ID 字段),您可以使用 inner join:

CREATE VIEW `instock` AS
SELECT 
    table1.name AS name,
    table1.supl AS supply,
    table2.num AS numbers,
    table1.maxnum AS maxnumbers
FROM
    (table1
    INNER JOIN table2 ON ((table1.id = table2.id)))
ORDER BY table1.name

再说一次:这取决于您的需求。 IFNULL/COALESCE 将显示 0 而不是 NULL,INNER JOIN 将完全跳过这些行。

(有疑问时,我总是参考 this explanation on joins。值得一铸。)