飙血推荐
  • HTML教程
  • MySQL教程
  • JavaScript基础教程
  • php入门教程
  • JavaScript正则表达式运用
  • Excel函数教程
  • UEditor使用文档
  • AngularJS教程
  • ThinkPHP5.0教程

MySQL 多表关联查询 JOIN

时间:2021-12-04  作者:匿名  

在前面的章节中,我们一次从一个表中获取数据。这对于简单的应用来说已经足够了,但是在大多数真实世界的 MySQL 使用中,您经常需要在单个查询中从多个表中获取数据。

您可以在单个 SQL 查询中使用多个表。在 MySQL 中加入的行为是指将两个或多个表链接成一个表。

您可以在 SELECT、UPDATE 和 DELETE 语句中使用 JOINS 来连接 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()函数从使用连接的 MySQL 表中获取记录。此函数采用两个参数,成功时返回 TRUE,失败时返回 FALSE。

句法

$mysqli->query($sql,$resultmode)
不。参数及说明
1

$sql

必需 - 使用连接从多个表中获取记录的 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>

上面例子中sql语句$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';的含义是:tutorials_tbl作为表a,tcount_tbl作为表b,返回的表包含3个字段,a.tutorial_id, a.tutorial_author, b.tutorial_count。

输出

访问部署在 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 LEFT JOIN与简单连接不同。MySQL LEFT JOIN 对左侧的表增加额外信息。

如果我执行LEFT JOIN,我会以相同的方式获得所有匹配的记录,此外,我会为连接左表中的每个未匹配记录获得一条额外记录:从而确保(在我的示例中)每个 AUTHOR 获得提到。

例子

尝试以下示例以了解 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)

您需要做更多的练习才能熟悉 JOINS。这是 MySQL/SQL 中稍微有点复杂的概念,在做实际示例时会变得更加熟悉。

搜你所爱
MySQL教程:目录
湘ICP备14001474号-3  投诉建议:234161800@qq.com   部分内容来源于网络,如有侵权,请联系删除。