資料庫相關操作
#建立表
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
sex VARCHAR(10),
hometown VARCHAR(50),
age VARCHAR(10),
class VARCHAR(50)
)
#新增資料
INSERT INTO student VALUES
(1,'王昭君','女','北京',20,'1班'),
(2,'妲己','女','廣東',26,'2班'),
(3,'李白','男','河南',21,'1班'),
(4,'劉備','男','四川',32,'2班'),
(5,'諸葛亮','男','上海',18,'2班'),
(7,'白起','男','北京',22,'4班'),
(8,'大喬','女','天津',19,'3班'),
(9,'孫尚香','女','河北',18,'1班'),
(10,'百里玄策','男','山西',20,'2班'),
(11,'百里守約','男','上海',21,'1班'),
(12,'小喬','女','',15,'3班')
#查詢所有學生資訊
SELECT * FROM student
#查詢名字是李白的學生
SELECT * FROM student WHERE NAME='李白'
#查詢1班是上海的
SELECT * FROM student WHERE class='1班' AND hometown='上海'
#查詢家鄉是北京或上海的
SELECT * FROM student WHERE hometown='北京' OR hometown='上海'
#查詢小喬的年齡
SELECT NAME,age FROM student WHERE NAME='小喬'
#查詢家鄉不在北京的學生
SELECT * FROM student WHERE hometown NOT IN('北京')
#查詢年齡小於20的女同學
SELECT * FROM student WHERE sex='女' AND age<20
#查詢年齡為18至20的學生
SELECT * FROM student WHERE age>=18 AND age<=20
#查詢北京學生的年齡總和
SELECT SUM(age) FROM student WHERE hometown='北京'
#查詢女生的平均年齡
SELECT AVG(age) FROM student WHERE sex='女'
#查詢姓名包含白的學生
SELECT * FROM student WHERE NAME LIKE '%白%'
#查詢所有學生資訊,俺年齡從大到小排序,年齡相同時,再按學號從小到大排序
SELECT * FROM student ORDER BY age DESC,id
#查詢女生的最大年齡
SELECT NAME,MAX(age) FROM student WHERE sex='女'
#查詢北京學生的年齡總和
SELECT SUM(age) FROM student WHERE hometown='北京'
#查詢各種性別的人數
SELECT sex,COUNT(sex) FROM student GROUP BY sex
#查詢男生總人數
SELECT sex,COUNT(sex) FROM student WHERE sex='男'