MariaDB学习 专题
您的位置:database > MariaDB学习专题 > MariaDB Join数据联接语句
MariaDB Join数据联接语句
作者:--    发布时间:2019-11-20

在之前的讨论和示例中,我们检查了从单个表中检索,或从多个来源检索多个值。 大多数现实世界的数据操作要复杂得多,需要从多个表进行聚合,比较和检索。

join允许将两个或多个表合并到单个对象中。 它们通过select,update和delete语句使用。

使用join查看语句的一般语法如下所示 -

select column
from table_name1
inner join table_name2
on table_name1.column = table_name2.column;

注意joins的旧语法使用隐式连接和没有关键字。 可以使用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               |
+-------------+----------------+-----------------+

php脚本使用join

使用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
";
   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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册