表结构以及数据:
CREATE TABLE`student` (
`id`int(11) NOT NULLAUTO_INCREMENT,
`name`varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age`int(11) NULL DEFAULT NULL,PRIMARY KEY(`id`) USING BTREE
) ENGINE= InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
INSERT INTO `student` VALUES (1, 'zazr', 11);INSERT INTO `student` VALUES (2, 'jkg', 20);INSERT INTO `student` VALUES (4, 'zazr', 11);INSERT INTO `student` VALUES (5, 'jkg', 12);INSERT INTO `student` VALUES (6, 'lgh', 13);INSERT INTO `student` VALUES (7, 'zazr', 11);INSERT INTO `student` VALUES (8, 'jkg', 12);INSERT INTO `student` VALUES (9, 'lgh', 13);INSERT INTO `student` VALUES (10, 'zazr', 11);INSERT INTO `student` VALUES (11, 'jkg', 12);INSERT INTO `student` VALUES (12, 'lgh', 13);
查询表中所有数据:
SELECT * FROM student;
查询表中年龄的平均值:
SELECT ROUND(AVG(age),0) from student;
ROUND、AVG都是聚合函数,ROUND(小数,2)表示这个小数四舍五入保留2位小数;AVG求平均值
查询表中年龄大于等于平均值的学生姓名(子查询):
SELECT name FROM student WHERE age>=(SELECT ROUND(AVG(age),0) FROM student);
将表中的不同姓名插入到另一张NAME表中:
创建表:
CREATE TABLE NAME(
-> id int(11) NOT NULL AUTO_INCREMENT KEY,
-> name VARCHAR(20));
SQL语句:
INSERT name(name) SELECT name FROM student GROUP BY name;
将student表中的name值,替换成name表所对应的id(内连接):如果student的name等于name表中的name,则将student表中的name换成对应的id
UPDATE student INNER JOIN name ON name.name=student.name SET student.name=name.id;
此时可以看:id为1对应的是name表中id为3的名字:zazr
向student中添加两条记录:
INSERT student VALUES(NULL,"10",24);
INSERT student VALUES(NULL,"8",30);
向name中添加两条记录:
INSERT name VALUES(NULL,"张三");
INSERT name VALUES(NULL,"李四");
内连接:
查询student和name表满足相同条件的记录:student表中新加入的10和8,与name表中的id为4,5的没有对应关系,所以不会显示,条件就是student.name=name.id;
SELECT student.id,name.name FROM student INNER JOIN name ON student.name=name.id;
左外连接:显示左表中的全部以及与右表符合条件的记录
将查询改为左外连接查询:显示student全部id数据,不过对应的name为NULL;
SELECT student.id,name.name FROM student LEFT JOIN name ON student.name=name.id;
右外连接:
将查询改为右外连接查询:显示name全部name属性数据,不过对应的student的id为NULL;
SELECT student.id,name.name FROM student RIGHT JOIN name ON student.name=name.id;