开发学院

您的位置:首页>教程>正文

教程正文

MariaDB Join语句

MariaDB Join语句

  在前面的示例中,我们都是从单个表中检索数据,但是大多数项目的数据操作要复杂得多,需要从多个表中进行聚合、比较和检索。

  JOIN允许将两个或多个表合并成一个查询对象。它们通过选择、更新和删除语句来使用。

  查看JOIN语句的基本语法,如下所示:

SELECT column
FROM table_name1
INNER JOIN table_name2
ON table_name1.column = table_name2.column;

  注意JOIN的旧语法使用隐式连接,没有关键字。可以使用WHERE子句来实现连接,但是关键字在可读性、维护和最佳实践方面最有效。

  JOIN有多种形式,如左连接(left join)、右连接(right join)或内连接(inner 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               |
+-------------+----------------+-----------------+

PHP使用JOIN

  php使用mysql_query() 方法执行JOIN:

<?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