在之前的討論和示例中,我們檢查了從單個(gè)表中檢索,或從多個(gè)來源檢索多個(gè)值。 大多數(shù)現(xiàn)實(shí)世界的數(shù)據(jù)操作要復(fù)雜得多,需要從多個(gè)表進(jìn)行聚合,比較和檢索。
JOIN允許將兩個(gè)或多個(gè)表合并到單個(gè)對(duì)象中。 它們通過SELECT,UPDATE和DELETE語句使用。
使用JOIN查看語句的一般語法如下所示 -
SELECT column FROM table_name1 INNER JOIN table_name2 ON table_name1.column = table_name2.column;
注意JOINS的舊語法使用隱式連接和沒有關(guān)鍵字。 可以使用WHERE子句來實(shí)現(xiàn)聯(lián)接,但關(guān)鍵字最適合可讀性,維護(hù)和最佳實(shí)踐。
JOIN有許多形式,如左連接,右連接或內(nèi)連接。 各種連接類型基于共享值或特性提供不同類型的聚合。
在命令提示符或PHP腳本中使用JOIN。
在命令提示符下,只需使用標(biāo)準(zhǔn)語句 -
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 | +-------------+----------------+-----------------+
使用mysql_query()函數(shù)執(zhí)行連接操作 -
<?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); ?>
成功的數(shù)據(jù)檢索后,您將看到以下輸出 -
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
更多建議: