(编辑:jimmy 日期: 2024/12/27 浏览:2)
MySQL多表查询
添加练习表
-- 用户表(user) CREATE TABLE `user`( `id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '用户id(主键)', `username` VARCHAR(50) COMMENT '用户姓名', `age` CHAR(3) COMMENT '用户年龄' ); -- 订单表(orders) CREATE TABLE `orders`( `id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '订单id(主键)', `price` DOUBLE COMMENT '订单价格', `user_id` INT COMMENT '用户id(外键)' ); -- 给已经存在的表添加外键,语法如下 -- alter table 表名 add constraint [外键名字] foreign key (外键字段) references 父表(主键字段); ALTER TABLE orders ADD CONSTRAINT user_fk FOREIGN KEY (user_id) REFERENCES `user` (id); -- 向user表中添加数据 INSERT INTO USER VALUES(1,'第一',11); INSERT INTO USER VALUES(2,'小二',12); INSERT INTO USER VALUES(3,'张三',33); INSERT INTO USER VALUES(4,'李四',24); INSERT INTO USER VALUES(5,'王五',17); INSERT INTO USER VALUES(6,'赵六',36); INSERT INTO USER VALUES(7,'七七',18); INSERT INTO USER VALUES(8,'粑粑',NULL); -- 向orders 表中插入数据 INSERT INTO orders VALUES(111,1314,3); INSERT INTO orders VALUES(112,122,3); INSERT INTO orders VALUES(113,15,4); INSERT INTO orders VALUES(114,315,5); INSERT INTO orders VALUES(115,1014,NULL); INSERT INTO orders VALUES(116,666,6); INSERT INTO orders VALUES(117,1111,1); INSERT INTO orders VALUES(118,8888,NULL);
笛卡尔积
SELECT * FROM `user`,`orders`;
SELECT * FROM `user` AS u,`orders` AS o WHERE u.`id`=o.`user_id`;
1.内连接
1.1隐式内连接
SELECT * FROM `user` AS u,`orders` AS o WHERE u.`id`=o.`user_id`;
1.2显示内连接(推荐使用)
SELECT * FROM `user` u JOIN `orders` o ON u.`id`=o.`user_id` WHERE age >= 18;
2.外连接
2.1右外链接
SELECT * FROM `user` u RIGHT JOIN `orders` o ON u.`id`=o.`user_id`;
左边表数据(user)
右边表数据(orders)
2.2左外链接(推荐使用)
SELECT * FROM `user` u LEFT JOIN `orders` o ON u.`id`=o.`user_id`;
左边表数据(user)
右边表数据(orders)
3.子查询
SELECT * FROM orders o WHERE o.`user_id` IN ( SELECT u.`id` FROM `user` u WHERE u.`age` IN( SELECT MAX(u.`age`) FROM `user` u ) );
4.全连接(MySQL不支持)
MySQL其它文章,请看下面链接
MySQL DDL 语句
MySQL CRUD 语句
MySQL 聚合函数
MySQL 多表查询
END…