-- 用户表(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);
笛卡尔乘积是指在数学中,两个集合X和Y的笛卡尔积(Cartesian product),又称直积,表示为X × Y,第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员。
(笛卡尔积)百度百科
什么笛卡尔积,如下所示
SELECT * FROM `user`,`orders`;
SELECT * FROM `user` AS u,`orders` AS o WHERE u.`id`=o.`user_id`;
SELECT * FROM `user` AS u,`orders` AS o WHERE u.`id`=o.`user_id`;
SELECT * FROM `user` u JOIN `orders` o ON u.`id`=o.`user_id` WHERE age >= 18;
SELECT * FROM `user` u RIGHT JOIN `orders` o ON u.`id`=o.`user_id`;
SELECT * FROM `user` u LEFT JOIN `orders` o ON u.`id`=o.`user_id`;
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
)
);
MySQL DDL 语句
MySQL CRUD 语句
MySQL 聚合函数
MySQL 多表查询