视图不允许有空值

问题描述 投票:0回答:1

我有一个视图,显示几个不同对象的数据。

CREATE VIEW viewA AS
    SELECT
        fiel1, field2, field3, -- table 1
        field4, field5, field6, -- table 2
        field7, field8 -- table 3
    FROM table1 t1
       JOIN table2 t2 ON t1.t2id = t2.id
       JOIN table3 t3 ON t1.t3id = t3.id
GO

我的表如下。

CREATE TABLE table1 (
   id      int not null IDENTITY(1, 1),
   field1  int not null IDENTITY(1, 1),
   field2  int not null,
   field3  int not null,
   t2id    int, -- foreign key, is nullable
   t3id    int  -- foreign key, is nullable
);

CREATE TABLE table2 (
   id      int not null IDENTITY(1, 1),
   field4  int not null,
   field5 int not null,
   field6 varchar not null
);

CREATE TABLE table3 (
   id      int not null IDENTITY(1, 1),
   field7  int not null,
   field8 varchar not null
);

当我在table1中填入一些数据,而在t2id中没有填入任何数据时,视图没有填入数据,尽管id本身不是必须的。当我完成字段并在t2id中添加一些id时,数据被正确地显示出来。我尝试在 isnull(field7, null) as field7 但这并不能改变什么。

那么,是否可以让一个视图显示空值,即使字段本身不可空,但引用是空的?(我也试过用字段nullable来显示,但没有成功)。

sql-server sql-view
1个回答
1
投票

你使用了一个JOIN子句。请使用LEFT JOIN子句。

CREATE VIEW viewA AS
    SELECT
        fiel1, field2, field3, -- table 1
        field4, field5, field6, -- table 2
        field7, field8 -- table 3
    FROM table1 t1
       LEFT JOIN table2 t2 ON t1.t2id = t2.id
       LEFT JOIN table3 t3 ON t1.t3id = t3.id
GO

在这里了解更多关于SQL连接的信息。https:/www.w3schools.comsqlsql_join.asp

© www.soinside.com 2019 - 2024. All rights reserved.