在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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其它文章,请看下面链接 END… 到此这篇关于MySQL数据库高级查询和多表查询的文章就介绍到这了,更多相关MySQL高级查询和多表查询内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论