我的头痛已经开始,因为我试图制作这个MySQL视图,其中一个列的结果值为NULL。我需要有一个像0这样的实际值。
我从table1中获取我的id并在table2中对它进行比较,所以它不确定是否有一个带有该id的数字,如果table2中没有数字,则该值将变为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值
答案 0 :(得分:1)
您可以使用 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
答案 1 :(得分:1)
我不确定查询中的left join
。 left join
从 left 表(table1
)中提供所有行,包括那些在其他表中没有对应的行({{1} })。对于右表中这些不匹配的行,您将获得所有table2
列的NULL,包括table2
。
或许您正在寻找table2.num
。这取决于您的数据以及您的inner join
是否为NULL。要仅使用零替换NULL,请使用COALESCE
table2.num
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
如果您想完全跳过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
内的项目(与ID字段相对应),您可以使用table1
:
inner join
再次:这取决于您的需求。 IFNULL / COALESCE将显示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
而不是NULL,INNER JOIN将完全跳过这些行。
(如果有疑问,我总是提到this explanation on joins。这值得一试。)