ฐานข้อมูล MySQL (3) แสดงข้อมูลจากหลายตาราง

Computer Database 17 มกราคม พ.ศ. 2566 447
Home / Articles / 34

ในบทความนี้จะเป็นการแนะนำ "วิธีการใช้งาน ตาราง (Tables) มากกว่าหนึ่งตาราง ในฐานข้อมูล MySQL" ซึ่งตัวอย่างตารางที่ใช้ในบทความนี้ คือ ตารางที่ใช้เก็บประวัติการซื้อสินค้าของสมาชิก มีดังนี้

ตารางที่ 1 ตารางสมาชิก (members)

member_id name email
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;
Profile Picture.
  • Name (Pen name): Sunny Jirakit (Sunny420x)
  • Study: Bachelor Degree of Computer Science from Chiang Mai Rajabhat University
  • Personality: Architect (INTJ-T)
  • Experience: JavaScript,  Angular.js, React.js, Next.js  Express.js, Unity C#, Socket.io