mysql基础(附具体操作代码)
# 注释内容-- 注释内容--
创建数据库 kingCREATEDATABASE king;
-- 查看当前服务器下有哪些数据库
SHOW DATABASES;
SHOW SCHEMAS;
-- 查看king数据库的详细信息
SHOW CREATEDATABASE king;
-- 创建数据库queen 并且指定编码方式为gbk
CREATEDATABASEIFNOTEXISTS queen DEFAULTCHARACTERSET"GBK";
-- 查看当前服务器下全部的数据库
SHOW DATABASES;
-- 查看queen指定数据库的详细信息
SHOW CREATEDATABASE queen;
-- 将queen的数据库的编码方式改为utf8
ALTERDATABASE queen DEFAULTCHARACTERSET"UTF8";
-- 打开queen的数据库
USE queen;
-- 得到当前打开的数据库
SELECTDATABASE();
SELECTSCHEMA();
-- 删除king数据库
DROPDATABASEIFEXISTS king;
DROPDATABASEIFEXISTS queen;
-- 创建测试用数据库 testCREATEDATABASEIFNOTEXISTS test DEFAULTCHARACTERSET"UTF8";
-- 打开test
USE test;
-- 用户表 test_user
CREATETABLEIFNOTEXISTS test_user(
id INT,
username VARCHAR(20),
password CHAR(32),
email VARCHAR(50),
age TINYINT,
card CHAR(18),
tel CHAR(11),
salary FLOAT(8,2),
married TINYINT(1),
addr VARCHAR(100),
sex ENUM("男","女","保密")
)ENGINE=INNODB CHARSET=UTF8;
-- 查看test_user表的表结构
DESC test_user;
DESCRIBE test_user;
SHOW COLUMNS FROM test_user;
-- 删除test_user表
DROPTABLEIFEXISTS test_user;
-- 查看当前数据库下的数据表
-- 查看test_user表的详细信息
-- 通过三种方式查看指定数据表的表结构
-- 最后删除test_user数据表
数据库增加数据与查询数据
-- 用户表 test_userCREATETABLEIFNOTEXISTS test_user(
id INT,
username VARCHAR(20),
password CHAR(32),
email VARCHAR(50),
age TINYINT,
card CHAR(18),
tel CHAR(11),
salary FLOAT(8,2),
married TINYINT(1),
addr VARCHAR(100),
sex ENUM("男","女","保密")
)ENGINE=INNODB CHARSET=UTF8;
-- INSERT [INTO] tbl_name(id,username,...) VALUES(1,"KING",...);
-- 向test_user表插入一条记录
INSERT test_user(id,username,password,email,age,card,tel,salary,married,addr,sex)
VALUES(1,"king","king","965794175@qq.com",24,"xxxxxxxxxxxxxxxxxx","132xxxxxxxx",88888.68,0,"宁波","男");
-- 查询表中所有记录 SELECT * FROM tbl_name;
SELECT*FROM test_user;
INSERT test_user(id,username,password,email,age,card,tel,salary,married,addr,sex)
VALUES(-5,"king","123456","965794175@qq.com",190,"xxxxxxxxxxxxxxxxxx","132xxxxxxxx",2345.68,1,"宁波","女");
数据类型测试-测试整型+无符号+零填充
-- 测试整型CREATETABLE test_int(
a tinyint,
b smallint,
c mediumint,
d int,
e bigint
);
INSERT test_int(a) VALUES(-128);
-- 如果超出数据的范围,会产生截断现象
INSERT test_int(a) VALUES(-129);
INSERT test_int(a) VALUES(1270);
-- 测试无符号
CREATETABLE test_unsigned(
a tinyint,
b tinyint UNSIGNED
);
INSERT test_unsigned(a,b) VALUES(-12,-12);
INSERT test_unsigned(a,b) VALUES(0,0);
INSERT test_unsigned(a,b) VALUES(0,256);
-- 测试零填充 ZEROFILL
CREATETABLE test_int1(
a tinyint ZEROFILL,
b smallint ZEROFILL,
c mediumint ZEROFILL,
d int ZEROFILL,
e bigint ZEROFILL
);
INSERT test_int1(a,b,c,d,e) VALUES(1,1,1,1,1);
CREATETABLE test_int2(
a tinyint(2),
b smallint(2)
);
INSERT test_int2(a,b) VALUES(123,45678);
数据类型测试-测试浮点型
-- 测试浮点型CREATETABLE test_float(
a FLOAT(6,2),
b DOUBLE(6,2),
c DECIMAL(6,2)
);
INSERT test_float(a,b,c) VALUES(4.143,4.146,4.149);
CREATETABLE test_float1(
a FLOAT,
b DOUBLE,
c DECIMAL
);
INSERT test_float1(a,b,c) VALUES(4.143,4.146,4.649);
INSERT test_float(a,b,c) VALUES(1234567.89,2345678.9,567890.89);
数据类型测试-测试char和varchar+text+ENUM+set
-- 测试char 和 varcharCREATETABLE test_str(
a CHAR(5),
b VARCHAR(5)
);
INSERT test_str(a,b) VALUES("","");
INSERT test_str(a,b) VALUES("a","a");
INSERT test_str(a,b) VALUES("ab","ab");
INSERT test_str(a,b) VALUES("abc","abc");
INSERT test_str(a,b) VALUES("abcd","abcd");
INSERT test_str(a,b) VALUES("abcde","abcde");
INSERT test_str(a,b) VALUES("abcdef","abcdef");
INSERT test_str(a,b) VALUES(" 123 "," 123 ");
SELECT CONCAT("*",a,"*"),CONCAT("*",b,"*") FROM test_str;
-- 测试TEXT不能有默认值
CREATETABLE test_str1(
content TEXTDEFAULT"THIS IS A TEST"
);
-- 测试ENUM
CREATETABLE test_enum1(
sex ENUM("男","女 ","保密 ")
);
INSERT test_enum(sex) VALUES("男");
INSERT test_enum(sex) VALUES("男1");
INSERT test_enum(sex) VALUES(NULL);
INSERT test_enum(sex) VALUES(1);
INSERT test_enum(sex) VALUES(3);
INSERT test_enum(sex) VALUES(5);
-- 测试SET
CREATETABLE test_set(
a SET("A","B","C","D","E","F")
);
INSERT test_set(a) VALUES("A");
INSERT test_set(a) VALUES("C");
INSERT test_set(a) VALUES("C,D,E");
INSERT test_set(a) VALUES("C,F,A");
INSERT test_set(a) VALUES("C,F,A,H");
INSERT test_set(a) VALUES(2);
数据类型测试-测试时间类型
-- HH:MM:SS [D HH:MM:SS] D表示天数 0~34--
测试TIME类型CREATETABLE test_time(
a TIME
);
INSERT test_time(a) VALUES("12:23:45");
INSERT test_time(a) VALUES("2 12:23:45");
INSERT test_time(a) VALUES("22:22");
INSERT test_time(a) VALUES("22");
INSERT test_time(a) VALUES("2 22");
-- HHMMSS
INSERT test_time(a) VALUES("121212");
INSERT test_time(a) VALUES("0");
INSERT test_time(a) VALUES(0);
INSERT test_time(a) VALUES("787878");
INSERT test_time(a) VALUES(NOW());
INSERT test_time(a) VALUES(CURRENT_TIME);
-- 测试DATE类型 YYYY-MM-DD YYYYMMDD
CREATETABLE test_date(
a DATE
);
INSERT test_date(a) VALUES("2017-03-04");
INSERT test_date(a) VALUES("2017-2-13");
INSERT test_date(a) VALUES("4007-03-23");
INSERT test_date(a) VALUES("40071212");
INSERT test_date(a) VALUES("4007@12@12");
INSERT test_date(a) VALUES("4008#13#13");
INSERT test_date(a) VALUES("4009.8.14");
-- YY-MM-DD YYMMDD
-- 70~99 转换成1970~1999 00~69 2000~2069
INSERT test_date(a) VALUES("780902");
INSERT test_date(a) VALUES("650902");
INSERT test_date(a) VALUES("880902");
INSERT test_date(a) VALUES(NOW());
INSERT test_date(a) VALUES(CURRENT_DATE);
-- 测试DATETIME
CREATETABLE test_datetime(
a DATETIME
);
INSERT test_datetime(a) VALUES("1004-09-12 13:24:56");
INSERT test_datetime(a) VALUES("720305121212");
INSERT test_datetime(a) VALUES(NOW());
INSERT test_datetime(a) VALUES(DATETIME);
-- 测试TIMESTAMP
CREATETABLE test_timestamp(
a TIMESTAMP
);
INSERT test_timestamp(a) VALUES("1978-10-23 12:12:12");
-- 插入CURRENT_TIMESTAMP
INSERT test_timestamp VALUES(CURRENT_TIMESTAMP);
-- 插入NULL
INSERT test_timestamp VALUES(NULL);
-- 什么也不写 得到当前系统日期和时间
INSERT test_timestamp VALUES();
-- 测试YEAR
CREATETABLE test_year(
a YEAR
);
INSERT test_year(a) VALUES(1901);
-- 00~69 2000~2069 70~99 1970~1999
-- 0 插入的结果是0000
-- "0" 插入的结果是2000
数据类型测试-测试主键+复合主键+自增
-- 测试主键CREATETABLE test_primary_key(
id INT UNSIGNED PRIMARYKEY,
username VARCHAR(20)
);
INSERT test_primary_key(id,username) VALUES(1,"king");
INSERT test_primary_key(id,username) VALUES(1,"king123");
INSERT test_primary_key(username) VALUES("QUEEN");
CREATETABLE test_primary_key1(
id INT UNSIGNED KEY,
username VARCHAR(20)
);
CREATETABLE test_primary_key2(
id INT UNSIGNED,
username VARCHAR(20),
PRIMARYKEY(id)
);
-- CREATE TABLE test_primary_key3(
-- id INT UNSIGNED PRIMARY KEY,
-- courseId INT UNSIGNED PRIMARY KEY,
-- username VARCHAR(20),
-- email VARCHAR(50)
-- );
-- 复合主键
CREATETABLE test_primary_key3(
id INT UNSIGNED,
courseId VARCHAR(20),
username VARCHAR(20),
email VARCHAR(50),
PRIMARYKEY(id,courseId)
);
-- 1-a
INSERT test_primary_key3(id,courseId,username,email)
VALUES(1,"a","king","965794175@qq.com");
INSERT test_primary_key3(id,courseId,username,email)
VALUES(1,"b","king","965794175@qq.com");
INSERT test_primary_key3(id,courseId,username,email)
VALUES(2,"a","king","965794175@qq.com");
INSERT test_primary_key3(id,courseId,username,email)
VALUES(1,"a","1king","965794175@qq.com");
-- 测试AUTO_INCREMENT
CREATETABLE test_auto_increment(
id INT UNSIGNED KEY AUTO_INCREMENT,
username VARCHAR(20)
);
INSERT test_auto_increment(username) VALUES("A");
INSERT test_auto_increment(username) VALUES("B");
INSERT test_auto_increment(username) VALUES("C");
INSERT test_auto_increment(id,username) VALUES(NULL,"E");
INSERT test_auto_increment(id,username) VALUES(DEFAULT,"F");
INSERT test_auto_increment(id,username) VALUES(15,"G");
数据类型测试-测试非空+默认值+唯一键
-- 测试非空CREATETABLE test_not_null(
a varchar(20),
b varchar(20) notnull
);
INSERT test_not_null(a,b) VALUES("","");
INSERT test_not_null(a,b) VALUES(NULL,NULL);
INSERT test_not_null(a,b) VALUES(NULL,"abc");
INSERT test_not_null(a) VALUES("TEST");
-- 测试默认值
CREATETABLE test_default(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULL,
age TINYINT UNSIGNED DEFAULT18,
email VARCHAR(50) NOTNULLDEFAULT"965794175@qq.com"
);
INSERT test_default(username) VALUES("A");
INSERT test_default(username,age,email) VALUES("B",30,"965794175@qq.com");
INSERT test_default(username,age,email) VALUES("C",NULL,"965794175@qq.com");
INSERT test_default(username,age,email) VALUES("D",NULL,NULL);
INSERT test_default(username,age,email) VALUES("D",NULL,DEFAULT);
CREATETABLE test_default1(
id INT UNSIGNED AUTO_INCREMENT KEY,
sex ENUM("a","b","c") NOTNULLDEFAULT"a"
);
-- 测试UNIQUE KEY
CREATETABLE test_unique(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULLUNIQUEKEY,
email VARCHAR(50) UNIQUE,
card CHAR(18) UNIQUE
);
INSERT test_unique(username,email,card) VALUES("A","A@QQ.COM","1");
INSERT test_unique(username,email,card) VALUES("A","1A@QQ.COM","12");
INSERT test_unique(username,email,card) VALUES("B",NULL,NULL);
INSERT test_unique(username,email,card) VALUES("C",NULL,NULL);
数据类型测试-测试布尔类型
-- 用户表test_userCREATETABLEIFNOTEXISTS `test_user`(
`id` INT UNSIGNED AUTO_INCREMENT KEY COMMENT "用户编号",
`username` VARCHAR(20) NOTNULLUNIQUE COMMENT "用户名",
`password` CHAR(32) NOTNULL COMMENT "密码",
`email` VARCHAR(50) NOTNULLUNIQUE COMMENT "邮箱",
`age` TINYINT UNSIGNED NOTNULLDEFAULT18 COMMENT "年龄",
`sex` ENUM("男","女","保密") NOTNULLDEFAULT"保密" COMMENT "性别",
`tel` CHAR(11) NOTNULLUNIQUE COMMENT "电话",
`addr` VARCHAR(50) NOTNULLDEFAULT"北京" COMMENT "地址",
`card` CHAR(18) NOTNULLUNIQUE COMMENT "身份证号",
`married` TINYINT(1) NOTNULLDEFAULT0 COMMENT "0代表未结婚,1代表已结婚",
`salary` FLOAT(8,2) NOTNULLDEFAULT0 COMMENT "薪水"
)ENGINE=INNODB DEFAULT CHARSET=UTF8;
-- 测试布尔类型
CREATETABLE test_bool(
id int,
married BOOL
);
CREATETABLE test_bool1(
id int,
married BOOLEAN
);
对数据表字段的增删改
-- 测试添加和删除字段CREATETABLEIFNOTEXISTS user1(
id INT UNSIGNED AUTO_INCREMENT KEY
);
-- 添加用户名字段 username VARCHAR(20)
ALTERTABLE user1
ADD username VARCHAR(20);
-- 添加密码字段 password CHAR(32) NOT NULL
ALTERTABLE user1
ADD password CHAR(32) NOTNULL;
-- 添加邮箱字段 email VARCHAR(50) NOT NULL UNIQUE 加到username之后
ALTERTABLE user1
ADD email VARCHAR(50) NOTNULLUNIQUE AFTER username;
-- 添加测试字段 test TINYINT(1) NOT NULL DEFAULT 0; 加到首位
ALTERTABLE user1
ADD test TINYINT(1) NOTNULLDEFAULT0 FIRST;
-- 删除test字段
ALTERTABLE user1
DROP test;
-- 添加age、addr字段,删除email字段
ALTERTABLE user1
ADD age TINYINT UNSIGNED NOTNULLDEFAULT18,
ADD addr VARCHAR(100) NOTNULLDEFAULT"北京",
DROP email;
-- 创建数据表 id / proName
-- 添加price FLOAT(8,2) UNSIGNED NOT NULL DEFAULT 0
-- 添加num INT UNSIGNED NOT NULL DEFAULT 100
-- 添加测试字段test VARCHAR(50) NOT NULL 加到首位
-- 添加测试字段test1 CHAR(23) NOT NULL 添加到price之后
-- 删除test字段
-- 选中一次数据表完成多次操作,添加一个desc TEXT, 添加isSale 布尔类型 0下架 1代表在卖
-- 删除test1字段
-- 测试添加删除默认值操作
CREATETABLE user2(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULL,
age TINYINT UNSIGNED NOTNULLDEFAULT18,
email VARCHAR(50) NOTNULL
);
-- 给email字段添加默认值 test@qq.com
ALTERTABLE user2
ALTER email SETDEFAULT"test@qq.com";
-- 删除age字段的默认值
ALTERTABLE user2
ALTER age DROPDEFAULT;
-- 添加地址字段
-- 给地址字段添加默认值为北京
-- 删除商品数量的默认值
-- 测试修改字段类型和字段属性、字段名称
CREATETABLE user3(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(5) NOTNULLUNIQUE,
password CHAR(32) NOTNULL,
email VARCHAR(10) NOTNULL
);
-- 将用户名字段的类型改为20
ALTERTABLE user3
MODIFY username VARCHAR(20) NOTNULL;
-- 将密码的长度改为40
ALTERTABLE user3
MODIFY password CHAR(40) NOTNULL;
-- 将email字段改为VARCHAR(50) NOT NULL FIRST
ALTERTABLE user3
MODIFY email VARCHAR(50) NOTNULL FIRST;
-- 将username 名称改为user
ALTERTABLE user3
CHANGE username userVARCHAR(20) NOTNULL;
-- 将password 名称改为pwd
ALTERTABLE user3
CHANGE password pwd CHAR(40) NOTNULL;
-- 将email改成userEmail 类型改成VARCHAR(100) DEFAULT "test@qq.com"
ALTERTABLE user3
CHANGE email userEmail VARCHAR(100) DEFAULT"test@qq.com";
-- 测试添加和删除主键
CREATETABLE user4(
id INT UNSIGNED,
username VARCHAR(20) NOTNULL
);
-- 添加主键
ALTERTABLE user4
ADDPRIMARYKEY(id);
-- 删除主键
ALTERTABLE user4
DROPPRIMARYKEY;
CREATETABLE user5(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULL
);
-- 将id的AUTO_INCREMENT去掉
ALTERTABLE user5
MODIFY id INT UNSIGNED;
-- 测试添加和删除唯一
CREATETABLE user6(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULLUNIQUE,
password CHAR(32) NOTNULL,
email VARCHAR(50) NOTNULLUNIQUE
);
-- 删除唯一索引 username 和email
ALTERTABLE user6
DROPINDEX username;
ALTERTABLE user6
DROPINDEX email;
-- 添加唯一索引
ALTERTABLE user6
ADDUNIQUEKEY(username);
ALTERTABLE user6
ADDUNIQUEINDEX uni_email(email);
-- 将user6改为user666
ALTERTABLE user6
RENAME TO user666;
ALTERTABLE user666
RENAME AS user6;
ALTERTABLE user6
RENAME user666;
RENAME TABLE user666 TO user6;
存储引擎
-- 测试MEMORY存储引擎CREATETABLE m1(
a VARCHAR(100)
)ENGINE=MEMORY;
-- 测试CSV存储引擎
CREATETABLE c1(
a VARCHAR(20) NOTNULL,
b VARCHAR(20) NOTNULL
)ENGINE=CSV;
INSERT c1(a,b) VALUES("AAA","BBB");
INSERT c1(a,b) VALUES("CCC","DDD");
-- 测试ARCHIVE存储引擎
CREATETABLE a1 ASSELECT*FROM INFORMATION_SCHEMA.columns;
INSERTINTO a1 SELECT*FROM a1;
-- 11026432 57177
CREATETABLE a2 ENGINE=ARCHIVE ASSELECT*FROM a1;
-- 742354 55392
-- 测试MyISAM存储引擎
CREATETABLE test_myisam(
a INT UNSIGNED,
b VARCHAR(20),
c CHAR(32)
)ENGINE=MyISAM;
CREATETABLE myisam_1(
a char(30),
id int
)ENGINE=MyISAM;
CREATETABLE myisam_2(
a VARCHAR(30),
id int
)ENGINE=MyISAM;
CREATETABLE myisam_3(
a VARCHAR(30),
id int
)ENGINE=MyISAM ROW_FORMAT=FIXED;
CREATETABLE test_innodb(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULL
);
添加数据
-- 测试添加记录CREATEDATABASEIFNOTEXISTS king DEFAULTCHARACTERSET"UTF8";
USE king;
CREATETABLEIFNOTEXISTSuser(
id INT UNSIGNED AUTO_INCREMENT KEY COMMENT "编号",
username VARCHAR(20) NOTNULLUNIQUE COMMENT "用户名",
age TINYINT UNSIGNED DEFAULT18 COMMENT "年龄",
email VARCHAR(50) NOTNULLDEFAULT"test@qq.com" COMMENT "邮箱"
)ENGINE=INNODB CHARSET=UTF8;
-- 不指定字段名称
INSERTuser VALUE(1,"king",24,"965794175@qq.com");
INSERTuserVALUES(NULL,"queen",25,"queen@qq.com");
INSERTuserVALUES(DEFAULT,"lily",26,"lily@qq.com");
-- 列出指定字段的形式
INSERTuser(username,email) VALUES("rose","rose@qq.com");
INSERTuser(age,email,id,username) VALUES(34,"test@qq.com",5,"test");
-- 一次插入3条记录
INSERTuserVALUES(NULL,"a",DEFAULT,DEFAULT),
(NULL,"b",56,"b@qq.com"),
(NULL,"c",14,"c@qq.com");
-- INSERT ...SET 的形式
INSERTuserSET username="d",age=45,email="d@qq.com";
-- INSERT SELECT
INSERTuser(username) SELECT a FROM test;
修改删除数据
-- 测试更新语句--
修改第一个用户的信息 id=1UPDATEuserSET age=29WHERE id=1;
-- 修改id=3的用户,username age email
UPDATEuserSET age=47,email="lilys@qq.com",username="lilys"WHERE id=3;
-- 所有用户年龄+10
UPDATEuserSET age=age+10;
-- 将id<=5的用户年龄改为-20,将邮箱改为默认值
UPDATEuserSET age=age-20,email=DEFAULTWHERE id<=5;
-- 测试删除语句
-- 删除用户名为king
DELETEFROMuserWHERE username="king";
-- 删除年龄为24的用户
DELETEFROMuserWHERE age=24;
-- 删除表中所有记录
DELETEFROMuser;
INSERTuserVALUES(NULL,"queen",25,"queen@qq.com");
INSERTuserVALUES(DEFAULT,"lily",26,"lily@qq.com");
查询操作
-- 测试查询操作CREATETABLE user1(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULLUNIQUE COMMENT "编号",
age TINYINT UNSIGNED NOTNULLDEFAULT18 COMMENT "年龄",
sex ENUM("男","女","保密") NOTNULLDEFAULT"保密" COMMENT "性别",
addr VARCHAR(20) NOTNULLDEFAULT"宁波",
married TINYINT(1) NOTNULLDEFAULT0 COMMENT "0代表未结婚,1代表已婚",
salary FLOAT(8,2) NOTNULLDEFAULT0 COMMENT "薪水"
)ENGINE=INNODB CHARSET=UTF8;
INSERT user1 VALUES(1,"king",23,"男","宁波",1,50000);
INSERT user1(username,age,sex,addr,married,salary) VALUES("queen",27,"女","上海",0,25000);
INSERT user1 SET username="test",age=31,sex="女",addr="宁波",salary=40000;
INSERT user1 VALUES(NULL,"张三",38,"男","上海",0,15000),
(NULL,"张三风",38,"男","上海",0,15000),
(NULL,"张子怡",39,"女","宁波",1,85000),
(NULL,"汪峰",42,"男","深圳",1,95000),
(NULL,"刘德华",58,"男","广州",0,115000),
(NULL,"吴亦凡",28,"男","宁波",0,75000),
(NULL,"奶茶妹",18,"女","宁波",1,65000),
(NULL,"刘嘉玲",36,"女","广州",0,15000);
-- 查询表中所有记录
SELECT*FROM user1;
-- username,addr,age
SELECT username,addr,age FROM user1;
-- 查询king数据库下user1表中的所有记录
SELECT*FROM king.user1;
-- 查询user1表中的id 编号 username 用户名 sex 性别
SELECT id AS"编号",username AS"用户名", sex AS"性别"
FROM user1;
SELECT id age,age id,username FROM user1;
-- 给表起别名
SELECT id,username FROM user1 AS u;
-- 测试表名.字段名
SELECT user1.id,user1.username,user1.age FROM user1 ;
SELECT u.id,u.username,u.addr,u.sex FROM user1 AS u;
-- 测试WHERE 条件的比较运算符
-- 查询id,username,age id=5的用户
SELECT id,username,age FROM user1
WHERE id=5;
SELECT id,username,age FROM user1
WHERE id=50;
-- 添加desc字段 VARCHAR(100)
ALTERTABLE user1
ADD userDesc VARCHAR(100);
-- 更新id<=9的用户 userDesc="this is a test"
UPDATE user1 SET userDesc="this is a test"
WHERE id<=9;
-- 查询用户userDesc 为NULL的用户
SELECT id,username,age,userDesc FROM user1
WHERE userDesc=NULL;
-- 检测NULL值
SELECT id,username,age,userDesc FROM user1
WHERE userDesc<=>NULL;
-- IS [NOT] NULL检测NULL值
SELECT id,username,age,userDesc FROM user1
WHERE userDesc ISNULL;
-- 测试范围BETWEEN AND
-- 查询年龄在18~30之间的用户
SELECT id,username,age,sex FROM user1
WHERE age BETWEEN18AND30;
-- 查询薪水在10000~50000之间的用户
SELECT id,username,age,salary FROM user1
WHERE salary BETWEEN10000AND50000;
SELECT id,username,age,salary FROM user1
WHERE salary NOTBETWEEN10000AND50000;
-- 测试指定集合 IN
-- 查询编号为1,3,5,7,9
SELECT id,username,age FROM user1
WHERE id IN(1,3,5,7,9,29,45,78);
SELECT id,username,age FROM user1
WHERE username IN("king","queen","lily","rose");
-- 测试逻辑运算符
-- 查询性别为男并且年龄>=20的用户
SELECT id,username,age,sex FROM user1
WHERE sex="男"AND age>=20;
-- id>=5 && age<=30
SELECT id,username,age,sex FROM user1
WHERE id>=5AND age<=30;
SELECT id,username,age,sex FROM user1
WHERE id>=5AND age<=30AND sex="男";
-- 要求sex="女" 并且 addr="宁波"
SELECT id,username,age,sex,addr FROM user1
WHERE sex="女"AND addr="宁波";
-- 查询薪水范围在60000~10000并且性别为男 addr="宁波"
SELECT id,username,age,sex,salary,addr FROM user1
WHERE salary BETWEEN60000AND100000AND sex="男"AND addr="宁波";
-- 查询id=1 或者 用户名为queen
SELECT id,username,age FROM user1
WHERE id=1OR username="queen";
-- 测试模糊查询
SELECT id,username,age FROM user1
WHERE username="king";
SELECT id,username,age FROM user1
WHERE username LIKE"king";
-- 要求用户名中包含三
SELECT id,username,age,sex FROM user1
WHERE username LIKE"%三%";
-- 用户名中包含n
SELECT id,username,age FROM user1
WHERE username LIKE"%in%";
-- 要求查询出姓张的用户
SELECT id,username,age FROM user1
WHERE username LIKE"张%";
-- 查询以风结尾的用户
SELECT id,username,age FROM user1
WHERE username LIKE"%风";
-- 用户名长度为三位的用户
SELECT id,username,age,sex FROM user1
WHERE username LIKE"___";
SELECT id,username,age,sex FROM user1
WHERE username LIKE"张_";
SELECT id,username,age,sex FROM user1
WHERE username LIKE"张_%";
-- 测试分组
-- 按照性别分组sex
SELECT id,username,age,sex FROM user1
GROUPBY sex;
-- 按照addr分组
SELECT username,age,sex,addr FROM user1
GROUPBY addr;
-- 按照性别分组,查询组中的用户名有哪些
SELECT GROUP_CONCAT(username),age,sex,addr FROM user1
GROUPBY sex;
SELECT GROUP_CONCAT(username),age,sex,GROUP_CONCAT(addr) FROM user1
GROUPBY sex;
-- 测试COUNT()
SELECTCOUNT(*) FROM user1;
SELECTCOUNT(id) FROM user1;
-- 按照sex分组,得到用户名详情,并且分别组中的总人数
SELECT sex,GROUP_CONCAT(username) AS usersDetail,COUNT(*) AS totalUsers FROM user1
GROUPBY sex;
-- 按照addr分组,得到用户名的详情,总人数,得到组中年龄的总和,年龄的最大值、最小值、平均值和
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(age) AS sum_age,
MAX(age) AS max_age,
MIN(age) AS min_age,
AVG(age) AS avg_age
FROM user1
GROUPBY addr;
-- 按照sex分组,统计组中总人数、用户名详情,得到薪水总和,薪水最大值、最小值、平均值
SELECT sex,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(salary) AS sum_salary,
MAX(salary) AS max_salary,
MIN(salary) AS min_salary,
AVG(salary) AS avg_salary
FROM user1
GROUPBY sex;
SELECT GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers
FROM user1
GROUPBY sex
WITH ROLLUP;
-- 按照字段的位置来分组
SELECT id,sex,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(salary) AS sum_salary,
MAX(salary) AS max_salary,
MIN(salary) AS min_salary,
AVG(salary) AS avg_salary
FROM user1
GROUPBY2;
-- 查询age>=30的用户并且按照sex分组
SELECT sex,GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers
FROM user1
WHERE age>=30
GROUPBY sex;
-- 按照addr分组,统计总人数
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers
FROM user1
GROUPBY addr;
-- 对于分组结果进行二次筛选,条件是组中总人数>=3
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers
FROM user1
GROUPBY addr
HAVINGCOUNT(*)>=3;
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers
FROM user1
GROUPBY addr
HAVING totalUsers>=3;
-- 按照addr分组,
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(salary) AS sum_salary,
MAX(salary) AS max_salary,
MIN(salary) AS min_salary,
AVG(salary) AS avg_salary
FROM user1
GROUPBY addr;
-- 要求平均薪水>=40000
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(salary) AS sum_salary,
MAX(salary) AS max_salary,
MIN(salary) AS min_salary,
AVG(salary) AS avg_salary
FROM user1
GROUPBY addr
HAVING avg_salary>=40000;
-- 测试排序
-- 按照id降序排列
SELECT id,username,age
FROM user1
ORDERBY id DESC;
-- 按照age升序
SELECT id,username,age
FROM user1
ORDERBY age ;
-- 按照多个字段排序
SELECT id,username,age
FROM user1
ORDERBY age ASC,id ASC;
-- 测试条件+排序
SELECT id,username,age
FROM user1
WHERE age>=30;
SELECT id,username,age
FROM user1
WHERE age>=30
ORDERBY age DESC;
-- 实现随机记录
SELECT id,username,age
FROM user1
ORDERBYRAND();
-- 测试LIMIT语句
-- 显示结果集的前5条记录
SELECT id,username,age,sex
FROM user1
LIMIT 5;
SELECT id,username,age,sex
FROM user1
LIMIT 0,5;
-- 显示前3条记录
SELECT id,username,age,sex
FROM user1
LIMIT 0,3;
SELECT id,username,age,sex
FROM user1
LIMIT 3,3;
-- 更新前3条记录,将age+5
UPDATE user1 SET age=age+5 LIMIT 3;
-- 按照id降序排列,更新前三条记录,将age-10
UPDATE user1 SET age=age-10ORDERBY id DESC LIMIT 3;
-- 删除前三条记录
DELETEFROM user1
LIMIT 3;
DELETEFROM user1
ORDERBY id DESC
LIMIT 3;
-- 测试完整SELECT 语句的形式
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(age) AS sum_age,
MAX(age) AS max_age,
MIN(age) AS min_age,
AVG(age) AS avg_age
FROM user1
WHERE id>=2
GROUPBY addr;
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(age) AS sum_age,
MAX(age) AS max_age,
MIN(age) AS min_age,
AVG(age) AS avg_age
FROM user1
WHERE id>=2
GROUPBY addr
HAVING totalUsers>=2;
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(age) AS sum_age,
MAX(age) AS max_age,
MIN(age) AS min_age,
AVG(age) AS avg_age
FROM user1
WHERE id>=2
GROUPBY addr
HAVING totalUsers>=2
ORDERBY totalUsers ASC;
SELECT addr,
GROUP_CONCAT(username) AS usersDetail,
COUNT(*) AS totalUsers,
SUM(age) AS sum_age,
MAX(age) AS max_age,
MIN(age) AS min_age,
AVG(age) AS avg_age
FROM user1
WHERE id>=2
GROUPBY addr
HAVING totalUsers>=2
ORDERBY totalUsers ASC
LIMIT 0,2;
多表查询
CREATEDATABASEIFNOTEXISTS test2 DEFAULTCHARACTERSET"UTF8";USE test2;CREATETABLE emp(id
INT UNSIGNED AUTO_INCREMENT KEY,username
VARCHAR(20) NOTNULLUNIQUE COMMENT "编号",age
TINYINT UNSIGNED NOTNULLDEFAULT18 COMMENT "年龄",sex ENUM(
"男","女","保密") NOTNULLDEFAULT"保密" COMMENT "性别",addr
VARCHAR(20) NOTNULLDEFAULT"宁波",depId
TINYINT UNSIGNED NOTNULL COMMENT "部门对应的编号")ENGINE
=INNODB CHARSET=UTF8;INSERT emp(username,age,depId) VALUES("king",24,1),(
"queen",25,2),(
"test",26,1),(
"lily",27,1),(
"rose",28,3),(
"john",29,3);INSERT emp(username,age,depId) VALUES("测试用户",39,6);CREATETABLE dep(id
TINYINT UNSIGNED AUTO_INCREMENT KEY,depName
VARCHAR(50) NOTNULLUNIQUE,depDesc
VARCHAR(100) NOTNULLDEFAULT"")ENGINE
=INNODB CHARSET=UTF8;INSERT dep(depName,depDesc) VALUES("PHP教学部","研发PHP课件"),(
"JAVA教学部","研发JAVA课件"),(
"WEB前端教学部","研发WEB前端课件"),(
"IOS教学部","研发IOS课件");-- 查询 emp id username age 部门名称 dep depNameSELECT emp.id,emp.username,emp.age,dep.depName FROM emp,dep;
SELECT e.id,e.username,e.age,d.depName
FROM emp AS e
INNERJOIN dep AS d
ON e.depId=d.id;
-- 查询emp id username age addr dep id depName depDesc
SELECT e.id,e.username,e.age,e.addr,
d.id,d.depName,d.depDesc
FROM dep AS d
JOIN emp AS e
ON d.id=e.depId;
-- 测试左外连接
SELECT e.id,e.username,e.age,d.depName,d.depDesc
FROM emp AS e
LEFTOUTERJOIN dep AS d
ON e.depId=d.id;
-- 测试右外连接
SELECT e.id,e.username,e.age,d.depName,d.depDesc
FROM emp AS e
RIGHTJOIN dep AS d
ON e.depId=d.id;
实例
-- 创建管理员表CREATETABLEuser(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULLUNIQUE,
email VARCHAR(50) NOTNULLDEFAULT"382771946@qq.com",
proName VARCHAR(10) NOTNULLDEFAULT"北京"
);
INSERTuser(username,proName) VALUES("a","北京"),
("b","哈尔滨"),
("c","上海"),
("d","深圳"),
("e","广州"),
("f","重启");
-- 创建省份表
CREATETABLE provinces(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
proName VARCHAR(10) NOTNULLUNIQUE
);
INSERT provinces(proName) VALUES("北京"),
("上海"),
("深圳");
--
CREATETABLEuser(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULLUNIQUE,
email VARCHAR(50) NOTNULLDEFAULT"965794175@qq.com",
proId TINYINT UNSIGNED NOTNULL
);
INSERTuser(username,proId) VALUES("a",1);
INSERTuser(username,proId) VALUES("b",1);
INSERTuser(username,proId) VALUES("c",1);
INSERTuser(username,proId) VALUES("d",2);
INSERTuser(username,proId) VALUES("e",3);
INSERTuser(username,proId) VALUES("f",1);
INSERTuser(username,proId) VALUES("g",1);
-- 查询user id ,username provinces proName
SELECT u.id,u.username,p.proName
FROMuserAS u
JOIN provinces AS p
ON u.proId=p.id;
-- 创建省份表
CREATETABLE provinces(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
proName VARCHAR(10) NOTNULLUNIQUE
);
-- 管理员admin id username email proId
CREATETABLE admin(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULLUNIQUE,
email VARCHAR(50) NOTNULLDEFAULT"382771946@qq.com",
proId TINYINT UNSIGNED NOTNULL
);
INSERT admin(username,proId) VALUES("king",1);
INSERT admin(username,proId) VALUES("queen",2);
-- 商品分类cate id cateName cateDesc
CREATETABLE cate(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
cateName VARCHAR(50) NOTNULLUNIQUE,
cateDesc VARCHAR(100) NOTNULLDEFAULT""
);
INSERT cate(cateName) VALUES("母婴");
INSERT cate(cateName) VALUES("服装");
INSERT cate(cateName) VALUES("电子");
-- 商品表products id productName, price,cateId
CREATETABLE products(
id INT UNSIGNED AUTO_INCREMENT KEY,
productName VARCHAR(50) NOTNULLUNIQUE,
price FLOAT(8,2) NOTNULLDEFAULT0,
cateId TINYINT UNSIGNED NOTNULL,
adminId TINYINT UNSIGNED NOTNULL
);
INSERT products(productName,price,cateId,adminId)
VALUES("iphone9",9888,3,1),
("adidas",388,2,2),
("nike",888,2,2),
("奶瓶",288,1,1);
-- 查询products id productName price --- cate cateName
SELECT p.id,p.productName,p.price,c.cateName
FROM products AS p
JOIN cate AS c
ON p.cateId=c.id;
-- 查询管理员 id username email -- provinces proName
SELECT a.id,a.username,a.email,p.proName
FROM admin AS a
JOIN provinces AS p
ON a.proId=p.id;
-- 查询 products id productName price
-- cate cateName
-- admin username email
SELECT p.id,p.productName,p.price,c.cateName,a.username,a.email
FROM products AS p
JOIN admin AS a
ON p.adminId=a.id
JOIN cate AS c
ON p.cateId=c.id
WHERE p.price<1000
ORDERBY p.price DESC
LIMIT 0,2;
-- products id productName price
-- cate cateName
-- admin username email
-- provinces proName
测试外键
-- 测试外键--
新闻分类表 news_cateCREATETABLE news_cate(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
cateName VARCHAR(50) NOTNULLUNIQUE,
cateDesc VARCHAR(100) NOTNULLDEFAULT""
);
-- 新闻表 news
CREATETABLE news(
id INT UNSIGNED AUTO_INCREMENT KEY,
title VARCHAR(100) NOTNULLUNIQUE,
content VARCHAR(1000) NOTNULL,
cateId TINYINT UNSIGNED NOTNULL
);
INSERT news_cate(cateName) VALUES("国内新闻"),
("国际新闻"),
("娱乐新闻"),
("体育新闻");
INSERT news(title,content,cateId) VALUES("a1","aaaa1",1),
("a2","aaaa2",1),
("a3","aaaa3",4),
("a4","aaaa4",2),
("a5","aaaa5",3);
-- 查询news id title content
-- news_cate cateName
SELECT n.id,n.title,n.content,c.cateName
FROM news AS n
JOIN news_cate AS c
ON n.cateId=c.id;
INSERT news(title,content,cateId) VALUES("a6","aaaa6",45);
-- 添加外键
-- 新闻分类表 news_cate
CREATETABLE news_cate(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
cateName VARCHAR(50) NOTNULLUNIQUE,
cateDesc VARCHAR(100) NOTNULLDEFAULT""
)ENGINE=INNODB;
-- 新闻表 news
CREATETABLE news(
id INT UNSIGNED AUTO_INCREMENT KEY,
title VARCHAR(100) NOTNULLUNIQUE,
content VARCHAR(1000) NOTNULL,
cateId TINYINT UNSIGNED NOTNULL,
FOREIGNKEY(cateId) REFERENCES news_cate(id)
)ENGINE=INNODB;
INSERT news_cate(cateName) VALUES("国内新闻"),
("国际新闻"),
("娱乐新闻"),
("体育新闻");
INSERT news(title,content,cateId) VALUES("a1","aaaa1",1),
("a2","aaaa2",1),
("a3","aaaa3",4),
("a4","aaaa4",2),
("a5","aaaa5",3);
-- 测试非法记录
INSERT news(title,content,cateId) VALUES("b1","bbbb1",8);
-- 测试删除父表中的记录 和删除父表
DELETEFROM news_cate WHERE id=1;
UPDATE news_cate SET id=10WHERE id=1;
INSERT news_cate(cateName) VALUES("教育新闻");
-- 将教育新闻 改成教育
UPDATE news_cate SET cateName="教育"WHERE id=5;
UPDATE news_cate SET id=50WHERE cateName="教育";
-- 添加外键名称
-- 新闻分类表 news_cate
CREATETABLE news_cate(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
cateName VARCHAR(50) NOTNULLUNIQUE,
cateDesc VARCHAR(100) NOTNULLDEFAULT""
)ENGINE=INNODB;
-- 新闻表 news
CREATETABLE news(
id INT UNSIGNED AUTO_INCREMENT KEY,
title VARCHAR(100) NOTNULLUNIQUE,
content VARCHAR(1000) NOTNULL,
cateId TINYINT UNSIGNED NOTNULL,
CONSTRAINT cateId_fk_newsCate FOREIGNKEY(cateId) REFERENCES news_cate(id)
)ENGINE=INNODB;
-- 删除外键
ALTERTABLE news
DROPFOREIGNKEY cateId_fk_newsCate;
-- 添加外键
ALTERTABLE news
ADDFOREIGNKEY(cateId) REFERENCES news_cate(id);
-- 删除外键
ALTERTABLE news
DROPFOREIGNKEY news_ibfk_1;
ALTERTABLE news
ADDCONSTRAINT cateId_fk_newsCate FOREIGNKEY(cateId) REFERENCES news_cate(id);
INSERT news_cate(cateName) VALUES("国内新闻"),
("国际新闻"),
("娱乐新闻"),
("体育新闻");
INSERT news(title,content,cateId) VALUES("a1","aaaa1",1),
("a2","aaaa2",1),
("a3","aaaa3",4),
("a4","aaaa4",2),
("a5","aaaa5",8);
ALTERTABLE news
ADDFOREIGNKEY(cateId) REFERENCES news_cate(id);
-- 指定级联操作 DELETE CASCADE UPDATE CASCADE
ALTERTABLE news
ADDFOREIGNKEY(cateId) REFERENCES news_cate(id)
ONDELETECASCADEONUPDATECASCADE;
测试子查询
-- 测试子查询--
测试由IN引发的子查询SELECT*FROM emp
WHERE depId IN (SELECT id FROM dep);
SELECT*FROM emp
WHERE depId NOTIN (SELECT id FROM dep);
-- 学员stu
CREATETABLE stu(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOTNULLUNIQUE,
score TINYINT UNSIGNED NOTNULL
);
INSERT stu(username,score) VALUES("king",95),
("queen",75),
("zhangsan",69),
("lisi",78),
("wangwu",87),
("zhaoliu",88),
("tianqi",98),
("ceshi",99),
("tiancai",50);
-- 分数级别level
CREATETABLElevel(
id tinyint UNSIGNED AUTO_INCREMENT KEY,
score TINYINT UNSIGNED COMMENT "分数"
);
INSERTlevel(score) VALUES(90),(80),(70);
-- 查询出成绩优秀的学员
SELECT score FROMlevelWHERE id=1;
SELECT id,username,score FROM stu
WHERE score>=(SELECT score FROMlevelWHERE id=1);
-- 查询出没有得到评级的学员
SELECT id,username,score FROM stu
WHERE score<=(SELECT score FROMlevelWHERE id=3);
-- 由EXISTS 引发的子查询
SELECT*FROM emp WHEREEXISTS (SELECT depName FROM dep WHERE id=10);
SELECT*FROM emp WHEREEXISTS (SELECT depName FROM dep WHERE id=1);
-- 带有ANY SOME ALL关键字的子查询
SELECT*FROM stu
WHERE score>=ANY(SELECT score FROMlevel);
SELECT*FROM stu
WHERE score>=SOME(SELECT score FROMlevel);
SELECT*FROM stu
WHERE score>=ALL(SELECT score FROMlevel);
SELECT*FROM stu
WHERE score<ALL(SELECT score FROMlevel);
SELECT*FROM stu
WHERE score=ANY(SELECT score FROMlevel);
SELECT*FROM stu
WHERE score!=ALL(SELECT score FROMlevel);
-- 创建一个user1表,id username
CREATETABLE user1(
id int UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20)
)SELECT id,username FROM emp;
-- 将user表中的用户名写入到user1表中
INSERT user1(username) SELECT username FROMuser;
-- 将stu表中的tiancai用户名添加到user2表中
INSERT user2 SET username=(SELECT username FROM stu WHERE id=9);
-- 去掉字段的重复值
SELECTDISTINCT(username) FROM user2;
-- 将user1和user2数据合并到一起
SELECT*FROM user1
UNION
SELECT*FROM user2;
测试自身连接
-- 测试自身连接CREATETABLE cate(
id SMALLINT UNSIGNED AUTO_INCREMENT KEY,
cateName VARCHAR(100) NOTNULLUNIQUE,
pId SMALLINT UNSIGNED NOTNULLDEFAULT0
);
INSERT cate(cateName,pId) VALUES("服装",0);
INSERT cate(cateName,pId) VALUES("数码",0);
INSERT cate(cateName,pId) VALUES("箱包",0);
INSERT cate(cateName,pId) VALUES("男装",1);
INSERT cate(cateName,pId) VALUES("女装",1);
INSERT cate(cateName,pId) VALUES("内衣",1);
INSERT cate(cateName,pId) VALUES("电视",2);
INSERT cate(cateName,pId) VALUES("冰箱",2);
INSERT cate(cateName,pId) VALUES("洗衣机",2);
INSERT cate(cateName,pId) VALUES("爱马仕",3);
INSERT cate(cateName,pId) VALUES("LV",3);
INSERT cate(cateName,pId) VALUES("GUCCI",3);
INSERT cate(cateName,pId) VALUES("夹克",4);
INSERT cate(cateName,pId) VALUES("衬衫",4);
INSERT cate(cateName,pId) VALUES("裤子",4);
INSERT cate(cateName,pId) VALUES("液晶电视",10);
INSERT cate(cateName,pId) VALUES("等离子电视",10);
INSERT cate(cateName,pId) VALUES("背投电视",10);
-- 查询所有的分类信息,并且得到其父分类
SELECT s.id,s.cateName AS sCateName,p.cateName AS pCateName
FROM cate AS s
LEFTJOIN cate AS p
ON s.pId=p.id;
-- 查询所有的分类及其子分类
SELECT p.id,p.cateName AS pCateName,s.cateName AS sCateName
FROM cate AS s
RIGHTJOIN cate AS p
ON s.pId=p.id;
-- 查询所有的分类并且得到子分类的数目
SELECT p.id,p.cateName AS pCateName,COUNT(s.cateName) AScount
FROM cate AS s
RIGHTJOIN cate AS p
ON s.pId=p.id
GROUPBY p.cateName
ORDERBY id ASC;
sCate 表
id | cateName | pId |
+----+-----------------+-----+
|1| 服装 |0|
|2| 数码 |0|
|3| 玩具 |0|
|4| 男装 |1|
|5| 女装 |1|
|6| 内衣 |1|
|10| 电视 |2|
|11| 冰箱 |2|
|12| 洗衣机 |2|
|13| 爱马仕 |3|
|14| LV |3|
|15| GUCCI |3|
|16| 夹克 |4|
|17| 衬衫 |4|
|18| 裤子 |4|
|19| 液晶电视 |10|
|20| 等离子电视 |10|
|21| 背投电视 |10
pCate
id | cateName | pId |
+----+-----------------+-----+
|1| 服装 |0|
|2| 数码 |0|
|3| 玩具 |0|
|4| 男装 |1|
|5| 女装 |1|
|6| 内衣 |1|
|10| 电视 |2|
|11| 冰箱 |2|
|12| 洗衣机 |2|
|13| 爱马仕 |3|
|14| LV |3|
|15| GUCCI |3|
|16| 夹克 |4|
|17| 衬衫 |4|
|18| 裤子 |4|
|19| 液晶电视 |10|
|20| 等离子电视 |10|
|21| 背投电视 |10
测试字符串函数
-- 测试字符串函数--
CHAR_LENGTH():得到字符串的字符数SELECT CHAR_LENGTH("abc");
-- LENGTH():返回字符串的长度
SELECT LENGTH("abc");
-- CONCAT(s1,s2,....):将字符串合并成一个字符串
SELECT CONCAT("a","b","c");
-- 如果字符串中包含NULL,返回拼接结果就是NULL
SELECT CONCAT("a","b","c",null);
-- CONCAT_WS(x,s1,s2,s2....):以指定分隔符拼接字符串
SELECT CONCAT_WS("-","a","b","c");
-- 如果null在拼接的内容中,则转化成空字符串
SELECT CONCAT_WS("-","a","b","c",null);
-- 如果分隔符为null,拼接的结果为null
SELECT CONCAT_WS(null,"a","b","c");
-- 将字符串转换成大写或者小写 UPPER()| UCASE() LOWER()|LCASE()
SELECTUPPER("hello king"),UCASE("hello imooc"),LOWER("HELLO ADMIN"),LCASE("HELLO EVERYBODY");
-- 字符串的反转REVERSE()
SELECTREVERSE("abc");
-- LEFT()|RIGHT():返回字符串的前几个字符或者后几个字符
SELECTLEFT("hello",2),RIGHT("hello",2);
-- LPAD()|RPAD():用字符串填充到指定长度
SELECT LPAD("abc",10,"?");
SELECT RPAD("abc",10,"!");
-- 去掉字符串两端的空格TRIM()|LTRIM()|RTRIM():
SELECT CONCAT("*",TRIM(" abc "),"*"),CONCAT("*",LTRIM(" abc "),"*"),CONCAT("*",RTRIM(" abc "),"*");
-- REPEAT():重复指定的次数
SELECT REPEAT("hello",3);
-- REPLACE():字符串
SELECTREPLACE("hello king","king","queen");
-- 截取字符串SUBSTRING
SELECTSUBSTRING("abcdef",1,3);
-- 比较字符串
SELECT STRCMP("a","b");
测试日期时间函数
-- 测试日期时间函数--
返回当前日期SELECT CURDATE(),CURRENT_DATE();
-- 返回当前时间
SELECT CURTIME(),CURRENT_TIME();
-- 返回当前的日期时间
SELECT NOW(),CURRENT_TIMESTAMP(),SYSDATE();
-- 返回日期中的月份和月份的名称
SELECTMONTH("2017-02-19");
SELECTMONTH(CURDATE()),MONTHNAME(CURDATE());
-- 返回星期几
SELECT DAYNAME(NOW());
-- 返回一周内的第几天,0代表星期一
SELECT DAYOFWEEK(NOW());
SELECT WEEK(NOW());
SELECTYEAR(NOW()),MONTH(NOW()),DAY(NOW()),HOUR(NOW()),MINUTE(NOW()),SECOND(NOW());
-- DATEDIFF()计算两个日期相差的天数
SELECTDATEDIFF("2019-03-06","2019-03-02");
其他函数测试
-- 测试其它常用函数SELECT VERSION(),CONNECTION_ID();
SELECTUSER(),CURRENT_USER(),SYSTEM_USER(),SESSION_USER();
-- 得到上一步插入操作产生AUTO_INCREMENT的值
SELECT LAST_INSERT_ID();
SELECT MD5("king");
-- PASSWORD():密码加密算法
SELECT PASSWORD("root");
以上是 mysql基础(附具体操作代码) 的全部内容, 来源链接: utcz.com/z/532021.html