天天看點

Sql的join和where的差別join動作步驟例子Leetcode 601 體育館的人流量思考題

知乎:sql連接配接查詢中on篩選與where篩選的差別

join動作步驟

  • 笛卡爾積(是邏輯步驟還是真實步驟?如果是真實步驟實在太占記憶體)
  • 應用on篩選條件,注意

    left join

    不影響左邊的基表,隻影響右邊的外表
  • 添加外部行,

    left join

    後行數應該和基表的行數相等,在第二步沒有關聯起來的,右邊加上null
  • 應用where篩選條件

例子

表main

Sql的join和where的差別join動作步驟例子Leetcode 601 體育館的人流量思考題

表ext

Sql的join和where的差別join動作步驟例子Leetcode 601 體育館的人流量思考題
select * from main left join ext on main.id=ext.id and ext.address<>'杭州';

           

結果就錯了:

Sql的join和where的差別join動作步驟例子Leetcode 601 體育館的人流量思考題

因為如上所說的第三步,加上了null的對應

改為如下就可以了

select * from main left join ext on main.id=ext.id where ext.address<>'杭州';

           

Leetcode 601 體育館的人流量

這個題目是很好的表關聯的考察

X 市建了一個新的體育館,每日人流量資訊被記錄在這三列資訊中:序号 (id)、日期 (visit_date)、 人流量 (people)。



請編寫一個查詢語句,找出人流量的高峰期。高峰期時,至少連續三行記錄中的人流量不少于100。



例如,表 stadium:



+------+------------+-----------+

| id   | visit_date | people    |

+------+------------+-----------+

| 1    | 2017-01-01 | 10        |

| 2    | 2017-01-02 | 109       |

| 3    | 2017-01-03 | 150       |

| 4    | 2017-01-04 | 99        |

| 5    | 2017-01-05 | 145       |

| 6    | 2017-01-06 | 1455      |

| 7    | 2017-01-07 | 199       |

| 8    | 2017-01-08 | 188       |

+------+------------+-----------+



對于上面的示例資料,輸出為:



+------+------------+-----------+

| id   | visit_date | people    |

+------+------------+-----------+

| 5    | 2017-01-05 | 145       |

| 6    | 2017-01-06 | 1455      |

| 7    | 2017-01-07 | 199       |

| 8    | 2017-01-08 | 188       |

+------+------------+-----------+



           

sql代碼如下

思路:自體表2次join,考慮3種情況,第一種是在第一個,第二種是在中間,第三種是在第三個,這樣會有重複的,是以查詢的時候加了一個去重

select distinct a.* from stadium a join stadium b join stadium c on 

(a.id+1=b.id and b.id+1=c.id

or

a.id-1=b.id and b.id-1=c.id

or

a.id-1=b.id and a.id+1=c.id)

where a.people>=100 and b.people>=100 and c.people>=100

order by a.id;

           

思考題

如果采用如下的語句形式,會如何?

select a.*,b.* from a  left join b on 1=0

           

這樣的語句會有傳回值,而且a中所有行都會傳回,而b中全部填null