1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| -- 初始化数据 CREATE TABLE my_class( m_id INT PRIMARY KEY AUTO_INCREMENT, m_name VARCHAR(32) NOT NULL UNIQUE, m_count INT NOT NULL DEFAULT 0 )CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO my_class VALUES (1, "33", 33), (2, "34", 34), (3, "35", 35), (4, "36", 36);
CREATE TABLE my_student ( m_id INT PRIMARY KEY AUTO_INCREMENT, m_name VARCHAR ( 32 ) UNIQUE NOT NULL, m_sex ENUM ( '男', '女', '保密' ) DEFAULT '保密', m_class INT NOT NULL, m_score INT ) CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO my_student VALUES (1, 'xiaoming', '男', 4, 98), (2, 'xiaogang', '女', 3, 68), (3, 'xiaohong', '男', 2, 81), (4, 'xiaolv', '女', 4, 75), (5, 'dabai', '男', 4, 43), (6, 'dahei', '女', 3, 89), (7, 'zhonglan', '男', 2, 92), (8, 'zhongzi', '保密', 3, 86), (9, 'xioaming', '保密', 1, 66);
-- 多表查询,交叉连接,查询到的是两张表的乘积(笛卡尔积) SELECT * FROM my_class, my_student;
-- 多表查询,内连接,将两张表的字段进行了比较 SELECT * FROM my_class, my_student WHERE my_class.m_id = my_student.m_class;
-- 左外连接查询, on 后面是查询条件,以左边的 my_class 为主,如果右边没有数据匹配,就填充 null SELECT * FROM my_class LEFT JOIN my_student ON my_class.m_id = my_student.m_class;
-- 子查询:外层查询的查询结果依赖于内层的查询, in 条件,结果是否在集合中 SELECT DISTINCT * FROM my_class WHERE m_id IN ( SELECT m_class FROM my_student WHERE m_sex = "女" );
-- 判断有没有任何一个同学分数大于 90, 如果有则输出前三名 SELECT * FROM my_student, my_class WHERE EXISTS ( SELECT m_score FROM my_student WHERE m_score > 90 )AND my_student.m_class = my_class.m_id ORDER BY m_score DESC LIMIT 0, 3; -- 如果有男生和任何一个女生的成绩相同就输出信息 SELECT * FROM my_student, my_class WHERE m_score = ANY ( SELECT m_score FROM my_student WHERE m_sex = "女" )AND my_student.m_class = my_class.m_id AND m_sex = "男"; -- 如果有男生的成绩大于任何一个女生的成绩就输出信息 SELECT * FROM my_student, my_class WHERE m_score > ALL ( SELECT m_score FROM my_student WHERE m_sex = "女" )AND my_class.m_id = my_student.m_class AND m_sex = "男";
|