วันจันทร์ที่ 2 กุมภาพันธ์ พ.ศ. 2552

การ JOIN แบบต่างๆ

SQL JOINS
SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.

การ join ประเภทต่างๆ เพื่อคิวรี่ข้อมูลจากตารางมากกว่า 2 ตารางขึ้นไป ขึ้นอยู่กับความสัมพันธ์ระหว่างคอลัมน์ที่ีมีอยู่ในตารางที่จะนำมา join กัน


Tables in a database are often related to each other with keys.
ตารางในฐานข้อมูลมักจะมีความสัมพันธ์กับตารางอื่นด้วย keys ของตาราง

A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.
Primary Key ก็คือคอลัมน์ที่มีค่าไม่ซ้ำกันในแต่ละแถวของตารางนั้นๆ วัตถุประสงค์ก็เพื่อผูกข้อมูล(bind data) เข้าด้วยกัน ข้ามตาราง โดยที่ไม่มีการซ้ำกันของข้อมูลในทุกๆ ตาราง

Look at the "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.
คอลัมน์ "P_Id" เป็น Primary Key ของตาราง "Persons" นั้นหมายความว่าจะไม่มีแถวใดๆ เลยที่มีค่าซ้ำหรือเหมือนกันกับแถวอื่น P_Id จะทำแยกระหว่างคนสองคนถึงแม้จะมีชื่อเหมือนกัน

Next, we have the "Orders" table:

O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to the persons in the "Persons" table without using their names.
Notice that the relationship between the two tables above is the "P_Id" column.
คอลัมน์ "O_Id" ก็เป็น primary key ของตาราง "Orders" เช่นกันและคอลัมน์ "P_Id" นี้ก็ได้อ้างถึงบุคคลในตาราง "Persons" โดยไม่ได้ใช้ชื่อจริงๆ (แต่ใช้รหัสแทน)
จะสังเกตเห็นว่า ทั้ง 2 ตารางข้างบนนี้จะมีความสัมพันธ์กันผ่านคอลัมน์ "P_Id"


...พักก่อน เด๋วมาทำต่อนะคับพี่น้อง อดใจรอนิสนึง...










credit : http://www.w3schools.com/Sql/sql_join.asp


0 ความคิดเห็น: