left join副表查詢條件影響了主表查詢結果

2021-10-25 17:35:41 字數 1540 閱讀 5423

sql**如下:

select

count

(r.id)

as weight ,r.

*,m.

*from room r left

join meeting m on m.room_id =r.id

where r.tenant_id =

1and r.is_del =

0and

(m.organizer_id =

7or m.organizer_id is

null

)group

by r.id,r.name

如上,meeting表是left join進來的表,room表是主表,按理說meeting表的判斷條件不會影響主表,但是實際測試發現:

sql語句1:

select

count

(r.id)

as weight ,r.

*,m.

*from room r left

join meeting m on m.room_id =r.id

where r.tenant_id =

1and r.is_del =

0group

by r.id,r.name

查出來的資料有8條;

sql語句2:

select

count

(r.id)

as weight ,r.

*,m.

*from room r left

join meeting m on m.room_id =r.id

where r.tenant_id =

1and r.is_del =

0and

(m.organizer_id =

7or m.organizer_id is

null

)group

by r.id,r.name

查出來的資料有7條;

即:

m.organizer_id =

7or m.organizer_id is

null

這個查詢條件過濾掉了一條room表的資料。

這裡看到這個查詢條件加在where後面,現在把他提前,放到on後where前,即:

select

count

(r.id)

as weight ,r.

*,m.

*from room r left

join meeting m on m.room_id =r.id and

(m.organizer_id =

7or m.organizer_id is

null

)where r.tenant_id =

1and r.is_del =

0group

by r.id,r.name

查出來的就是8條了

三張表的Left Join查詢

三張表 a id,b id,c id,要根據相同的id顯示三張表,做left join。select from a left join b on a.id b.id left join c on a.id c.id where b.id is notnull from條件後面的括號不能忘了。再分享一...

三張表的Left Join查詢

三張表 a id,b id,c id,要根據相同的id顯示三張表,做left join。select from a left join b on a.id b.id left join c on a.id c.id where b.id is notnull from條件後面的括號不能忘了。三張表 ...

查詢條件使用配置表 SQL Server

有時需要知道填入的客戶資訊是否完整,可以將完整性條件寫進sql 中,但是,維護起來會比較麻煩。所以考慮寫一張配置表,維護人員只需要改配置表的內容即可 現有如下問題,想得到某客戶資訊是否完整以及來呢西人資訊完整的數量 object storedprocedure dbo p dj custominfo...