SQL 高級語法 (二)

示例數據庫:

  • website表
+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Baidu        | https://www.baidu.com/     |  1     | USA   |
| 2  | 京東          | https://www.jd.com/       |  13    | CN     |
| 3  | 微博          | http://www.weibo.com/     |  20    | CN     |
| 5  | Facebook     | https://www.facebook.com/  |  3     | USA    |
| 7  | stackoverflow | http://stackoverflow.com/ |  0     | IND    |
+----+---------------+---------------------------+-------+---------+
  • access_log表
+-----+---------+-------+------------+
| aid | site_id | count | date       |
+-----+---------+-------+------------+
|   1 |       1 |    45 | 2016-05-10 |
|   2 |       3 |   100 | 2016-05-13 |
|   3 |       1 |   230 | 2016-05-14 |
|   4 |       2 |    10 | 2016-05-14 |
|   5 |       5 |   205 | 2016-05-14 |
|   6 |       4 |    13 | 2016-05-15 |
|   8 |       5 |   545 | 2016-05-16 |
|   9 |       3 |   201 | 2016-05-17 |
+-----+---------+-------+------------+

1、INNER JOIN 關鍵字

說明:INNER JOIN關鍵字在表中存在至少一個匹配時返回行

語法:

SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name;

實例:

SELECT websites.name, access_log.count, access_log.date FROM websites INNER JOIN access_log ON websites.id=access_log.site_id;

2、LEFT JOIN 關鍵字

說明:LEFT JOIN 關鍵字從左表(table1)返回所有的行,即使右表(table2)中沒有匹配。如果右表中沒有匹配,則結果爲 NULL

語法:

SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name;

實例:

把 websites 作爲左表,access_log 作爲右表

SELECT websites.name, access_log.count, access_log.date FROM websites LEFT JOIN access_log ON websites.id=access_log.site_id;

3、RIGHT JOIN 關鍵字

說明:RIGHT JOIN 關鍵字從右表(table2)返回所有的行,即使左表(table1)中沒有匹配。如果左表中沒有匹配,則結果爲 NULL

語法:

SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_name;

實例:

把 access_log 作爲左表,websites 作爲右表

 

SELECT websites.name, access_log.count, access_log.date FROM access_log RIGHT JOIN Websites ON access_log.site_id=websites.id

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章