ในบทความนี้จะเป็นการแนะนำ "วิธีการใช้งาน ตาราง (Tables) มากกว่าหนึ่งตาราง ในฐานข้อมูล MySQL" ซึ่งตัวอย่างตารางที่ใช้ในบทความนี้ คือ ตารางที่ใช้เก็บประวัติการซื้อสินค้าของสมาชิก มีดังนี้
ตารางที่ 1 ตารางสมาชิก (members)
| member_id | name | |
|---|---|---|
| 1 | Mr.A | [email protected] |
| 2 | Mr.B | [email protected] |
ตารางที่ 2 ตารางประวัติการสั่งซื้อ (orders)
| id | member_id | product_id | amount |
|---|---|---|---|
| 1 | 1 | P2 | 5 |
| 2 | 1 | P3 | 2 |
| 3 | 2 | P1 | 3 |
ตารางที่ 3 ตารางสินค้า (products)
| product_id | name | price |
|---|---|---|
| P1 | Coffee | 35 |
| P2 | Alcohol | 20 |
| P3 | Cigarette | 70 |
จะใช้คำสั่ง
select members.name, products.product_id,
orders.amount, products.price, sum(products.price * orders.amount) as total
from orders, products, members
where products.product_id = orders.product_id and
members.member_id = orders.member_id group by orders.product_id;
จากคำสั่งผมได้เลือกคอลัมน์ที่ชื่อว่า name จากตาราง members, product_id จากตาราง products, amount จากตาราง orders, price จากตาราง products และผมยังเพิ่มคอลัมน์อีกหนึ่งอันชื่อ total ซึ่งเก็บผลลัพท์ของ price จาก products คูณกับ amount จาก orders (ตัวหนา หมายถึง ชื่อตารางต่างๆ ที่เรียกใช้)
โดยมีเงื่อนไข where ว่า product_id จาก products ต้องเท่ากับ product_id ของ orders และ member_id ของ members ต้องเท่ากับ member_id ของ orders และทำการจัดกลุ่ม (Group By) จาก product_id ของ orders เหตุผลที่ต้องสร้างเงื่อนไขแบบนี้ เนื่องจากเราต้องการให้แถวแต่ละแถวในตารางตรงกันก่อน จึงจะสามารถได้ข้อมูล total ที่ถูกต้อง และแสดงข้อมูลจากตารางครบทั้งหมด
เพื่อนๆ สามารถลอง เปลี่ยนเงื่อนไขเป็นแบบอื่นได้ เพื่อดูปัญหาที่เกิดขึ้นหากใช้เงื่อนไขต่างออกไป
| name | product_id | amount | price | total |
|---|---|---|---|---|
|
Mr.B |
P1 |
3 | 35 | 105 |
|
Mr.A |
P2 |
5 | 20 | 100 |
|
Mr.A |
P3 |
2 | 70 | 140 |
หากย่อคำสั่งให้ชื่อตารางเก็บไว้ในตัวแปรสั้นๆ โดยการใช้คำสั่ง "as" จะได้คำสั่งดังนี้
select m.name, p.product_id, o.amount, p.price, sum(p.price * o.amount) as total
from orders as o, products as p, members as m
where p.product_id = o.product_id and m.member_id = o.member_id group by o.product_id;
