建立两张表:
①供应商vendors表,包含id和名字。
CREATE TABLE vendors ( id INT PRIMARY KEY, vendor_name VARCHAR(25) );
②商品表_products,包含供应商id(vendor_id),商品名(product_name)和商品价格(product_price)。
CREATE TABLE _products ( vendor_id INT, product_name VARCHAR(25), product_price DECIMAL(8, 2) );
插入数据:
INSERT INTO _products VALUES(1001, '香蕉', 9.8), (1001, '苹果', 12.81), (1002, '玉米', 20.8), (1002, '五谷杂粮', 30.81), (1003, '衣服', 20.99);
INSERT INTO vendors VALUES(1001, '怡馨家园'), (1002, '蔬果超市'), (1003, '亿嘉超市');
- INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
- LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
- RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
内连接演示
-- 查询提供衣服的供应商信息 SELECT product_name, id, vendor_name FROM vendors, _products WHERE vendors.`id` = _products.`vendor_id` AND _products.`product_name` = '衣服'; -- 第二种写法 SELECT id, product_name, vendor_name FROM vendors INNER JOIN _products ON vendors.`id` = _products.`vendor_id` AND _products.`product_name` = '玉米';
左连接演示
-- 左外链接 INSERT INTO vendors VALUES(1004, '零食屋'); SELECT vendor_name, product_name FROM vendors LEFT JOIN _products ON vendors.`id` = _products.`vendor_id`;
右连接演示
-- 右外联接 INSERT INTO _products VALUES(1005, '鞋子', 40.99); SELECT vendor_name, product_name FROM vendors RIGHT JOIN _products ON vendors.`id` = _products.`vendor_id`;
标签:product,vendor,name,vendors,products,mysql,联接,id From: https://www.cnblogs.com/dadishi/p/17066050.html