>  기사  >  데이터 베이스  >  MySQL 조인 사용법 튜토리얼

MySQL 조인 사용법 튜토리얼

零下一度
零下一度원래의
2017-05-15 10:21:551447검색

Mysql Join 사용법

이전 장에서는 하나의 테이블에서 데이터를 읽는 방법을 배웠습니다. 이는 비교적 간단하지만 실제 응용 프로그램에서는 여러 데이터 테이블에서 데이터를 읽어야 하는 경우가 많습니다. 데이터를 읽어옵니다.

이 장에서는 MySQL의 JOIN을 사용하여 두 개 이상의 테이블에 있는 데이터를 쿼리하는 방법을 소개합니다.

SELECT, UPDATE 및 DELETE 문에서 Mysql의 조인을 사용하여 여러 테이블 쿼리를 결합할 수 있습니다.

아래에서는 MySQL LEFT JOIN과 JOIN 사용의 차이점을 보여드리겠습니다.

명령 프롬프트에서 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>

다음으로 MySQL의 JOIN을 사용하여 위의 두 테이블을 연결하여 tutorials_tbl 테이블의 모든 tutorial_author 필드를 읽습니다. tcount_tbl 테이블에서 해당 tutorial_count 필드 값:

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 스크립트에서 JOIN 사용

PHP에서 mysql_query() 함수를 사용하여 SQL 문을 실행합니다. 위의 SQL 문을 mysql_query와 동일하게 사용할 수 있습니다. () 함수 매개변수.

다음 예를 시도해 보세요.

<?php$dbhost = &#39;localhost:3036&#39;;$dbuser = &#39;root&#39;;$dbpass = &#39;rootpassword&#39;;$conn = mysql_connect($dbhost, $dbuser, $dbpass);if(! $conn ){  die(&#39;Could not connect: &#39; . mysql_error());}$sql = &#39;SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count        FROM tutorials_tbl a, tcount_tbl b        WHERE a.tutorial_author = b.tutorial_author&#39;;mysql_select_db(&#39;TUTORIALS&#39;);$retval = mysql_query( $sql, $conn );if(! $retval ){  die(&#39;Could not get data: &#39; . mysql_error());}while($row = mysql_fetch_array($retval, MYSQL_ASSOC)){    echo "Author:{$row[&#39;tutorial_author&#39;]}  <br> ".         "Count: {$row[&#39;tutorial_count&#39;]} <br> ".         "Tutorial ID: {$row[&#39;tutorial_id&#39;]} <br> ".         "--------------------------------<br>";} echo "Fetched data successfully\n";mysql_close($conn);?>

MySQL LEFT JOIN

MySQL 왼쪽 조인은 조인과 다릅니다. MySQL LEFT JOIN은 오른쪽 테이블에 해당 데이터가 없더라도 왼쪽 데이터 테이블의 모든 데이터를 읽습니다.

尝试以下实例,理解MySQL LEFT JOIN的应用:
root@host# mysql -u root -p password;Enter password:*******mysql> use TUTORIALS;Database changedmysql> 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)

위의 예에서는 LEFT JOIN이 사용되었습니다. 이 문은 오른쪽 테이블 tcount_tbl에 해당 tutorial_author가 없더라도 왼쪽 데이터 테이블 tutorials_tbl에서 선택된 모든 필드 데이터를 읽습니다. . 필드 값.

【관련 추천】

1. 특별 추천: "php Programmer Toolbox" V0.1 버전 다운로드

2. 무료 mysql 온라인 동영상 튜토리얼

3. 데이터베이스 설계에 관한 것들

위 내용은 MySQL 조인 사용법 튜토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.