MySQLi - 使用連線



在之前的章節中,我們一次從一個表中獲取資料。這對於簡單的任務來說已經足夠了,但在大多數真實的 MySQL 使用場景中,您通常需要在單個查詢中從多個表中獲取資料。

您可以在單個 SQL 查詢中使用多個表。在 MySQL 中,連線是指將兩個或多個表合併成一個表。

您可以在 SELECT、UPDATE 和 DELETE 語句中使用 JOIN 來連線 MySQL 表。我們還將看到 LEFT JOIN 的示例,它與簡單的 MySQL JOIN 不同。

在命令提示符下使用連線

假設我們在 TUTORIALS 中有兩個表 **tcount_tbl** 和 **tutorials_tbl**。現在來看下面的例子:

示例

以下示例:

root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * FROM tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|      mahran     |       20       |     
|      mahnaz     |      NULL      |        
|       Jen       |      NULL      |          
|      Gill       |       20       |          
|    John Poul    |        1       |      
|     Sanjay      |        1       |        
+-----------------+----------------+
6 rows in set (0.01 sec)
mysql> SELECT * from tutorials_tbl;
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
|      1      |  Learn PHP     |     John Poul   |    2007-05-24   |   
|      2      |  Learn MySQL   |      Abdul S    |    2007-05-24   |   
|      3      | JAVA Tutorial  |      Sanjay     |    2007-05-06   |   
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.00 sec)
mysql>

現在我們可以編寫一個 SQL 查詢來連線這兩個表。此查詢將從 **tutorials_tbl** 表中選擇所有作者,並從 **tcount_tbl** 表中選擇相應的教程數量。

mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
   → FROM tutorials_tbl a, tcount_tbl b
   → WHERE a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
|      1      |    John Poul    |        1       |
|      3      |     Sanjay      |        1       |
+-------------+-----------------+----------------+
2 rows in set (0.01 sec)
mysql>

在 PHP 指令碼中使用連線

PHP 使用 **mysqli_query()** 或 **mysql_query()** 函式透過 JOIN 從 MySQL 表中獲取記錄。此函式接受兩個引數,成功時返回 TRUE,失敗時返回 FALSE。

語法

$mysqli→query($sql,$resultmode)

序號 引數和描述
1

$sql

必需 - 使用 JOIN 從多個表獲取記錄的 SQL 查詢。

2

$resultmode

可選 - 常量 MYSQLI_USE_RESULT 或 MYSQLI_STORE_RESULT 之一,具體取決於所需的行為。預設情況下,使用 MYSQLI_STORE_RESULT。

首先使用以下指令碼在 MySQL 中建立一個表並插入兩條記錄。

create table tcount_tbl(
   tutorial_author VARCHAR(40) NOT NULL,
   tutorial_count int
);
insert into tcount_tbl values('Mahesh', 3);
insert into tcount_tbl values('Suresh', 1);

示例

嘗試以下示例以使用 JOIN 從兩個表中獲取記錄:

複製並貼上以下示例作為 mysql_example.php:

<html>
   <head>
      <title>Using joins on MySQL Tables</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         
         if($mysqli→connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli→connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
   
         $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
				FROM tutorials_tbl a, tcount_tbl b
				WHERE a.tutorial_author = b.tutorial_author';
		 
         $result = $mysqli→query($sql);
           
         if ($result→num_rows > 0) {
            while($row = $result→fetch_assoc()) {
               printf("Id: %s, Author: %s, Count: %d <br />", 
                  $row["tutorial_id"], 
                  $row["tutorial_author"], 
                  $row["tutorial_count"]);               
            }
         } else {
            printf('No record found.<br />');
         }
         mysqli_free_result($result);
         $mysqli→close();
      ?>
   </body>
</html>

輸出

訪問部署在 Apache Web 伺服器上的 mysql_example.php 並驗證輸出。

Connected successfully.
Id: 1, Author: Mahesh, Count: 3
Id: 2, Author: Mahesh, Count: 3
Id: 3, Author: Mahesh, Count: 3
Id: 5, Author: Suresh, Count: 1

MySQL LEFT JOIN

MySQL 左連線與簡單的連線不同。MySQL LEFT JOIN 對左側的表給予額外的考慮。

如果我使用 **LEFT JOIN**,我會得到所有匹配的記錄,此外,我還為左表中每個不匹配的記錄獲得額外的記錄:因此,在我的示例中,確保每個作者都會被提及。

示例

嘗試以下示例以瞭解 LEFT JOIN。

root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
   → FROM tutorials_tbl a LEFT JOIN tcount_tbl b
   → ON a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
|      1      |    John Poul    |       1        |
|      2      |     Abdul S     |      NULL      |
|      3      |     Sanjay      |       1        |
+-------------+-----------------+----------------+
3 rows in set (0.02 sec)

您需要進行更多練習才能熟悉 JOIN。這在 MySQL/SQL 中是一個稍微有點複雜的概念,在進行實際示例時會變得更加清晰。

廣告
© . All rights reserved.