时间:2023-02-11 09:49:26 | 栏目:JAVA代码 | 点击:次
创建新表:
-- 创建学员表 CREATE TABLE IF NOT EXISTS stu( id TINYINT UNSIGNED AUTO_INCREMENT KEY COMMENT '编号', username VARCHAR(20) NOT NULL UNIQUE COMMENT '学员名称', score TINYINT UNSIGNED NOT NULL COMMENT '学员考试分数' )ENGINE=INNODB; INSERT stu(username, score) VALUES('king', 95), ('queen', 75), ('zhangsan', 69), ('lisi', 78), ('wangwu', 87), ('zhaoliu', 88), ('tianqi', 98), ('ceshi', 99), ('tiancai', 50); -- 创建分数级别表 CREATE TABLE IF NOT EXISTS `level`( id TINYINT UNSIGNED AUTO_INCREMENT KEY COMMENT '编号', score TINYINT UNSIGNED COMMENT '分数' )ENGINE=INNODB; INSERT `level`(score) VALUES(90), (80), (70);
SELECT * FROM user1 WHERE depId IN (1, 2, 3, 4); SELECT * FROM user1 WHERE depId IN (SELECT id FROM dep);
SELECT id, username, score FROM stu WHERE score >= (SELECT score FROM `level` WHERE id = 1);
若EXISTS后的结果为真,则返回查询的结果,否则返回结果为空。
SELECT * FROM stu WHERE EXISTS (SELECT score FROM `level` WHERE id = 1);
取ANY|SOME|ALL后的括号中的查询结果的最小值或最大值。
-- ANY SOME ALL SELECT * FROM stu WHERE score >= ANY(SELECT score FROM `level`); SELECT * FROM stu WHERE score > SOME(SELECT score FROM `level`); SELECT * FROM stu WHERE score > ALL(SELECT score FROM `level`);
-- 创建一个user3表,将表stu中的id, username的信息写入user3中 CREATE TABLE user3( id INT UNSIGNED AUTO_INCREMENT KEY, username VARCHAR(20) ) SELECT id, username FROM stu;
-- 将user1表中的username信息插入到user3中 INSERT user3(username) SELECT username FROM user1;
创建和表2结构相同的表1。
去掉两个表中的重复值。
SELECT 字段名称,… FROM 表名1 UNION SELECT 字段名称,… FROM 表名2;
只是将两个表进行简单的合并,不会去掉重复值。
SELECT 字段名称,… FROM 表名1 UNION ALL SELECT 字段名称,… FROM 表名2;
创建表cate:
-- 创建表cate CREATE TABLE cate( id SMALLINT UNSIGNED AUTO_INCREMENT KEY COMMENT '编号', cateName VARCHAR(100) NOT NULL UNIQUE COMMENT '分类名称', pId SMALLINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '父id' ); -- 插入顶级分类 INSERT cate(cateName, pId) VALUES('服装', 0), ('数码', 0), ('玩具', 0), -- 插入服装的子分类 ('男装', 1), ('女装', 1), ('内衣', 1), -- 插入数码的子分类 ('电视', 2), ('冰箱', 2), ('洗衣机', 2), -- 插入玩具的子分类 ('爱马仕', 3), ('LV', 3), ('GUCCI', 3), -- 插入男装的子分类 ('夹克', 4), ('衬衫', 4), ('裤子', 4), -- 插入电视的子分类 ('液晶电视', 7), ('等离子电视', 7), ('背投电视', 7);
自身连接:
-- 查询所有的分类信息,并且得到其父分类 SELECT s.id, s.cateName AS sCateName, p.cateName AS pCateName FROM cate AS s LEFT JOIN cate AS p ON s.pId = p.id;