gpt4 book ai didi

列为 NULL 的 MySQL View

转载 作者:行者123 更新时间:2023-11-29 02:17:43 26 4
gpt4 key购买 nike

自从我尝试创建此 MySQL View 以来,我的头痛就开始了,其中一列的结果值为 NULL。我需要一个像 0 这样的真实值。

我从表 1 中取出我的 ID 并在表 2 中进行比较,因此不确定是否有一个具有该 ID 的数字,如果表 2 中没有数字,该值将变为 NULL,而我需要的是 0。这是我的 View 代码:

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 值的列号

最佳答案

我不确定您在查询中的left joinleft join 给出 left 表 (table1) 中的所有 行,包括那些在其他表(table2)。对于右表中这些不匹配的行,您将获得所有 table2 列的 NULL,包括 table2.num

也许您正在寻找内部联接。这取决于您的数据以及您的 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 。值得一试。)

关于列为 NULL 的 MySQL View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36957646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com