到目前,我們已經(jīng)學(xué)習(xí)了從一個表中獲取數(shù)據(jù)。這是簡單的需要,但在大多數(shù)現(xiàn)實MySQL的使用,經(jīng)常需要將數(shù)據(jù)從多個表中的一個單一的查詢。
可以使用多個表中的單一SQL查詢。在MySQL中聯(lián)接(join)行為是指兩個或多個表到一個表中可以使用連接在SELECT,UPDATE和DELETE語句中加入MySQL表。我們將看到一個例子LEFT JOIN簡單的MySQL連接。
在命令提示符使用聯(lián)接:
假設(shè)我們兩個表的教程tcount_tbl和tutorials_tbl的完整列表如下:
例子:
試試下面的例子:
| root@host# mysql -u root -p password;Enter password:*******mysql> use TUTORIALS;Database changedmysql> 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> |
現(xiàn)在,加入這兩個表我們可以編寫一個SQL查詢。這個查詢會選擇所有的作者從表tutorials_tbl,從tcount_tbl會拿起相應(yīng)數(shù)量的教程。
| 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腳本中使用聯(lián)接:
可以使用任何上述的SQL查詢的PHP腳本。只需要通過PHP函數(shù)mysql_query()執(zhí)行SQL查詢,然后用常規(guī)方法獲取結(jié)果。
例子:
試試下面的例子:
| <?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.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a, tcount_tbl b WHERE a.tutorial_author = b.tutorial_author';mysql_select_db('TUTORIALS');$retval = mysql_query( $sql, $conn );if(! $retval ){ die('Could not get data: ' . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)){ echo "Author:{$row['tutorial_author']} <br> ". "Count: {$row['tutorial_count']} <br> ". "Tutorial ID: {$row['tutorial_id']} <br> ". "--------------------------------<br>";} echo "Fetched data successfully/n";mysql_close($conn);?> |