
- MariaDB 教程
- MariaDB - 首頁
- MariaDB - 簡介
- MariaDB - 安裝
- MariaDB - 管理
- MariaDB - PHP 語法
- MariaDB - 連線
- MariaDB - 建立資料庫
- MariaDB - 刪除資料庫
- MariaDB - 選擇資料庫
- MariaDB - 資料型別
- MariaDB - 建立表
- MariaDB - 刪除表
- MariaDB - 插入查詢
- MariaDB - 選擇查詢
- MariaDB - WHERE 子句
- MariaDB - 更新查詢
- MariaDB - 刪除查詢
- MariaDB - LIKE 子句
- MariaDB - ORDER BY 子句
- MariaDB - 聯接
- MariaDB - NULL 值
- MariaDB - 正則表示式
- MariaDB - 事務
- MariaDB - ALTER 命令
- 索引和統計表
- MariaDB - 臨時表
- MariaDB - 表克隆
- MariaDB - 序列
- MariaDB - 管理重複項
- MariaDB - SQL 注入保護
- MariaDB - 備份方法
- MariaDB - 備份載入方法
- MariaDB - 常用函式
- MariaDB 常用資源
- MariaDB - 快速指南
- MariaDB - 常用資源
- MariaDB - 討論
MariaDB - 聯接
在之前的討論和示例中,我們研究了從單個表中檢索資料,或者從多個來源檢索多個值。大多數現實世界的資料操作要複雜得多,需要聚合、比較和從多個表中檢索資料。
JOIN(聯接)允許將兩個或多個表合併成一個物件。它們透過 SELECT、UPDATE 和 DELETE 語句使用。
檢視下面所示使用 JOIN 的語句的通用語法:
SELECT column FROM table_name1 INNER JOIN table_name2 ON table_name1.column = table_name2.column;
請注意,舊的 JOIN 語法使用隱式聯接且沒有關鍵字。可以使用 WHERE 子句實現聯接,但是為了可讀性、維護性和最佳實踐,關鍵字更有效。
JOIN 有多種形式,例如左聯接、右聯接或內聯接。各種聯接型別根據共享值或特徵提供不同型別的聚合。
在命令提示符或使用 PHP 指令碼中使用 JOIN。
命令提示符
在命令提示符下,只需使用標準語句:
root@host# mysql -u root -p password; Enter password:******* mysql> use PRODUCTS; Database changed mysql> SELECT products.ID_number, products.Nomenclature, inventory.inventory_ct FROM products INNER JOIN inventory ON products.ID_numbeer = inventory.ID_number; +-------------+----------------+-----------------+ | ID_number | Nomenclature | Inventory Count | +-------------+----------------+-----------------+ | 12345 | Orbitron 4000 | 150 | +-------------+----------------+-----------------+ | 12346 | Orbitron 3000 | 200 | +-------------+----------------+-----------------+ | 12347 | Orbitron 1000 | 0 | +-------------+----------------+-----------------+
使用 JOIN 的 PHP 指令碼
使用mysql_query()函式執行聯接操作:
<?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'SELECT a.product_id, a.product_manufacturer, b.product_count FROM products_tbl a, pcount_tbl b WHERE a.product_manufacturer = b.product_manufacturer'; mysql_select_db('PRODUCTS'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Manufacturer:{$row['product_manufacturer']} <br> ". "Count: {$row['product_count']} <br> ". "Product ID: {$row['product_id']} <br> ". "--------------------------------<br>"; } echo "Fetched data successfully\n"; mysql_close($conn); ?>
成功檢索資料後,您將看到以下輸出:
ID Number: 12345 Nomenclature: Orbitron 4000 Inventory Count: 150 -------------------------------------- ID Number: 12346 Nomenclature: Orbitron 3000 Inventory Count: 200 -------------------------------------- ID Number: 12347 Nomenclature: Orbitron 1000 Inventory Count: 0 -------------------------------------- mysql> Fetched data successfully
廣告