左连接不返回ull值

时间:2016-09-27 16:00:05

标签: sql sql-server tsql

我有两张桌子:

AppWindowsEvent:

CREATE TABLE [AppWindowsEvent]
(
[idAppWindowEvent]      INT IDENTITY(1,1)
, [idAppWindow]         INT
, [idEventType]         INT
, [Order]               INT
, CONSTRAINT PK_idAppWindowEvent PRIMARY KEY ([idAppWindowEvent])
, CONSTRAINT FK_idAppWindowEvent_AppWindow FOREIGN KEY ([idAppWindow]) REFERENCES [AppWindow]([idAppWindow])
, CONSTRAINT FK_idAppWindowEvent_EventType FOREIGN KEY ([idEventType]) REFERENCES [EventType]([idEventType])
)

事件:

CREATE TABLE [Event]       
(
[idEvent] [INT] IDENTITY(1,1) NOT NULL
, [idEventType] [INT] NOT NULL
, [idEntity] [INT] NOT NULL
, CONSTRAINT PK_IdEvent PRIMARY KEY([idEvent])
, CONSTRAINT [FK_Event_EventType] FOREIGN KEY([idEventType]) REFERENCES [EventType] ([idEventType])
)

当我运行此查询时:

SELECT
*
FROM
AppWindowsEvent AWE
LEFT JOIN Event E ON AWE.idEventType = E.idEventType
WHERE
AWE.idMill = 1
AND AWE.idAppWindow = 1
ORDER BY
AWE.[Order] ASC

结果:不返回空值。

当我运行这个

SELECT
*
FROM
AppWindowsEvent AWE
LEFT JOIN Event E ON AWE.idEventType = E.idEventType
AND E.[idEntity] = 1234
WHERE
AWE.idMill = 1
AND AWE.idAppWindow = 1
ORDER BY
AWE.[Order] ASC

结果:返回空值。

注意: 我需要已经配置的整个数据集,如果你想要一组特定的事件,在AND的ON中可以通过Event表的特定idEntity进行过滤,结果返回得很好,但仅限于此idEntity,在我的情况下,我需要所有idEntity。

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT *
FROM
AppWindowsEvent AWE
LEFT JOIN Event E ON AWE.idEventType = E.idEventType 
WHERE
AWE.idMill = 1
AND AWE.idAppWindow = 1
AND E.[idEntity] = 1234
ORDER BY
AWE.[Order] ASC

或者,如果您不想在第二个表中显示null valor,则可以使用Inner Join而不是Left Join

SELECT *
FROM
AppWindowsEvent AWE
Inner JOIN Event E ON AWE.idEventType = E.idEventType 
AND E.[idEntity] = 1234
WHERE
AWE.idMill = 1
AND AWE.idAppWindow = 1
ORDER BY
AWE.[Order] ASC