1. 程式人生 > >MySQL Crash Course #07# Chapter 15 關系數據庫. INNER JOIN. VS. nested subquery

MySQL Crash Course #07# Chapter 15 關系數據庫. INNER JOIN. VS. nested subquery

itl enables cts 測試 each rst not with dex

索引

  • 理解相關表. foreign key
  • JOIN 與保持參照完整性
  • 關於JOIN 的一些建議,子查詢 VS. 聯表查詢

我發現 MySQL 的文檔裏是有教程的,不過對於概念貌似沒有提及,只是告訴你怎麽樣(語句),沒有告訴你前因後果(原理)。想看有生動解釋的書,例如會給各種 JOIN 畫 VN 圖的那種,也不知道該怎麽找(好像應該搜 SQL tutorial 而不是 MySQL tutorial)。

SQL Tutorial - W3Schools

The SQL Tutorial for Data Analysis | SQL Tutorial - Mode Analytics

Understanding Relational Tables

The key here is that having multiple occurrences of the same data is never a good thing, and that principle is the basis for relational database design. Relational tables are designed so information is split into multiple tables, one for each data type. The tables are related to each other through common values (and thus the relational in relational design).

書上舉了一個產品表和供應商表的例子,一個供應商可以對應很多的產品,不把供應商的信息放在每一行產品的理由有如下幾點:

  1. 多個產品的供應商是一致的,重復相同的信息很浪費空間
  2. 如果供應商的信息改變,你不得不更新每一條該供應商相關的產品記錄
  3. 很大概率出現數據不一致的情況

所以產品和供應商應該分兩張表存,兩張表都應該有 primary key , 供應商表專門存供應商的信息,而產品表專門存產品的信息,每一個產品記錄除了包含一個供應商的 id 屬性不應該包含任何供應商的其他信息,這個屬性對應的字段叫做 foreign key (和供應商表的 primary key 相關系)這麽做有如下幾個好處:

  1. 沒有重復數據,節省時間和空間
  2. 需要修改供應商信息時只需要修改一處就好了
  3. 因為數據沒有被重復,很好的保證了數據一致性

Why Use Joins?

As just explained, breaking data into multiple tables enables more efficient storage(高效存儲), easier manipulation(易於操作), and greater scalability(極高的可擴展性). But these benefits come with a price.

If data is stored in multiple tables, how can you retrieve that data with a single SELECT statement?

The answer is to use a join.

It is important to understand that a join is not a physical entity in other words, it does not exist in the actual database tables. A join is created by MySQL as needed, and it persists for the duration of the query execution.

- maintaining referential integrity 是說 MySQL 只允許合法的數據(foreign key 的值在主表中存在的數據)插入到關系表中。

Creating a Join

SELECT vend_name, prod_name, prod_price
FROM vendors, products
ORDER BY vend_name, prod_name;
SELECT vend_name, prod_name, prod_price
FROM vendors INNER JOIN products
 ON vendors.vend_id = products.vend_id;
  1. 雖然默認就是 inner join (就是會臨時創建 x * x 表的那個),但是最好還是用 INNER JOIN ON 語句,這樣你就再也不會忘記 JOIN 的類型了。
  2. JOIN 是在運行時臨時做的,關聯的表越多越消耗資源,所以不必要就不要亂聯表

It Pays to Experiment As you can see, there is often more than one way to perform any given SQL operation. And there is rarely a definitive right or wrong way. Performance can be affected by the type of operation, the amount of data in the tables, whether indexes and keys are present, and a whole slew of other criteria. Therefore, it is often worth experimenting with different selection mechanisms to find the one that works best for you.

聯表快還是子查詢快取決於具體情況,所以在必要時候可以進行測試。。 。問題 在於 。。 如何測試?? -- > 待更新

MySQL Crash Course #07# Chapter 15 關系數據庫. INNER JOIN. VS. nested subquery