SQL - MySql
คำสั่ง sql Select ข้อมูลสองตาราง Mysql ใช้ได้ กับ Sql มาตรฐาน ใช้การ Joins Left Join, Right Join, Inner Join
ตัวอย่างมีตารางข้อมูล
ตาราง products; +----+--------------+--------------+ | id | product_name | manufacturer | +----+--------------+--------------+ | 1 | Shoes | Company1 | | 2 | Laptop | Company2 | | 3 | Monitor | Company3 | | 4 | DVD | Company4 | +----+--------------+--------------+
ตาราง buyers;
+----+------+------------+----------+ | id | pid | buyer_name | quantity | +----+------+------------+----------+ | 1 | 1 | Steve | 2 | | 2 | 2 | John | 1 | | 3 | 3 | Larry | 1 | | 4 | 3 | Michael | 5 | | 5 | NULL | Steven | NULL | +----+------+------------+----------+
การ Join ตารางแบบ Left Join เป็นการค้นหาข้อมูลจากสองตารางโดยยึดตาราง ทางซ้ายเป็นหลัก ในที่นี่ตารางซ้ายคือ buyers ต้องมีข้อมูล
SELECT buyer_name, quantity, product_name FROM buyers LEFT JOIN products ON buyers.pid=products.id;ผล
+------------+----------+--------------+ | buyer_name | quantity | product_name | +------------+----------+--------------+ | Steve | 2 | Shoes | | John | 1 | Laptop | | Larry | 1 | Monitor | | Michael | 5 | Monitor | | Steven | NULL | NULL | +------------+----------+--------------+ การ Join ตาราง แบบ Right Join เป็นการค้นหาข้อมูลจากสองตารางโดยยึดตาราง ทางซ้ายเป็นหลัก ในที่นี่ตารางขวาคือ products ต้องมีข้อมูล
SELECT buyer_name, quantity, product_name FROM buyers RIGHT JOIN products ON buyers.pid=products.id; +------------+----------+--------------+ | buyer_name | quantity | product_name | +------------+----------+--------------+ | Steve | 2 | Shoes | | John | 1 | Laptop | | Larry | 1 | Monitor | | Michael | 5 | Monitor | | NULL | NULL | DVD | +------------+----------+--------------+
การ Join ตารางแบบ Inner join ข้อมูลที่จะออกมาต้องมีทั้งในตาราง ซ้ายและขวา เครื่องหมาย= (buyers.pid=products.id) SELECT buyer_name, quantity, product_name FROM buyers INNER JOIN products ON buyers.pid=products.id;ลองเอาไปรันดูผล
สำหรับตารางข้อมูล มากกว่า สองตารางก็ใช้หลักการเดียวกัน
|
|
เขียนโดย Mysql Join
วันเสาร์ที่ 01 พฤษภาคม 2010 เวลา 00:00 น.