MySQL在单字段上模糊查询多个关键字

select * from '表名' where '模糊查询字段' regexp 'key1|key2|key3|...' and '其它字段' = '其它字段值' and ...

示例:查询姓名为张三,年龄为18,家庭地址在花园路,幸福路,安康路的所有人

select * from user_info where user_name = '张三' and age = 18 and address regexp '花园路|幸福路|安康路';
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
查询数据指从数据库中获取所需要的数据。查询数据是数据库操作中最常用,也是最重要的操作。用户可以根据自己对数据的需求,使用不同的查询方式。通过不同的查询方式,可以获得不同的数据。MySQL中是使用SELECT语句来查询数据的。在这一章中将讲解的内容包括。 1、查询语句的基本语法 2、在表上查询数据 3、使用聚合函数查询数据 4、多表上联合查询 5、子查询 6、合并查询结果 7、为表和字段取别名 8、使用正则表达式查询 什么是查询? 怎么查的? 数据的准备如下: [sql] view plain copy create table STUDENT( STU_ID int primary KEY, STU_NAME char(10) not null, STU_AGE smallint unsigned not null, STU_SEX char(2) not null ); insert into STUDENT values(2001,'小王',13,'男'); insert into STUDENT values(2002,'明明',12,'男'); insert into STUDENT values(2003,'红红',14,'女'); insert into STUDENT values(2004,'小花',13,'女'); insert into STUDENT values(2005,'天儿',15,'男'); insert into STUDENT values(2006,'阿猎',13,'女'); insert into STUDENT values(2007,'阿猫',16,'男'); insert into STUDENT values(2008,'阿狗',17,'男'); insert into STUDENT values(2009,'黑子',14,'男'); insert into STUDENT values(2010,'小玉',13,'女'); insert into STUDENT values(2011,'头头',13,'女'); insert into STUDENT values(2012,'冰冰',14,'女'); insert into STUDENT values(2013,'美丽',13,'女'); insert into STUDENT values(2014,'神乐',12,'男'); insert into STUDENT values(2015,'天五',13,'男'); insert into STUDENT values(2016,'小三',11,'男'); insert into STUDENT values(2017,'阿张',13,'男'); insert into STUDENT values(2018,'阿杰',13,'男'); insert into STUDENT values(2019,'阿宝',13,'女'); insert into STUDENT values(2020,'大王',14,'男'); 然后这是学生成绩表,其中定义了外键约束 [sql] view plain copy create table GRADE( STU_ID INT NOT NULL, STU_SCORE INT, foreign key(STU_ID) references STUDENT(STU_ID) ); insert into GRADE values(2001,90); insert into GRADE values(2002,89); insert into GRADE values(2003,67); insert into GRADE values(2004,78); insert into GRADE values(2005,89); insert into GRADE values(2006,78); insert into GRADE values(2007,99); insert into GRADE values(2008,87); insert into GRADE values(2009,70); insert into GRADE values(2010,71); insert into GRADE values(2011,56); insert into GRADE values(2012,85); insert into GRADE values(2013,65); insert into GRADE values(2014,66); insert into GRADE values(2015,77); insert into GRADE values(2016,79); insert into GRADE values(2017,82); insert into GRADE values(2018,88); insert into GRADE values(2019,NULL); insert into GRADE values(2020,NULL); 一、查询语句的基本语法 查询数据是指从数据库中的数据表或视图中获取所需要的数据,在mysql中,可以使用SELECT语句来查询数据。根据查询条件的不同,数据库系统会找到不同的数据。 SELECT语句的基本语法格式如下: [sql] view plain copy SELECT 属性列表 FROM 表名或视图列表 [WHERE 条件表达式1] [GROUP BY 属性名1 [HAVING 条件表达式2]] [ORDER BY 属性名2 [ASC|DESC]] 属性列表:表示需要查询的字段名。 表名或视图列表:表示即将进行数据查询的数据表或者视图,表或视图可以有多个。 条件表达式1:设置查询的条件。 属性名1:表示按该字段中的数据进行分组。 条件表达式2:表示满足该表达式的数据才能输出。 属性2:表示按该字段中的数据进行排序,排序方式由ASC或DESC参数指定。 ASC:表示按升序的顺序进行排序。即表示值按照从小到大的顺序排列。这是默认参数。 DESC:表示按降序的顺序进行排序。即表示值按照从大到小的顺序排列。 如果有WHERE子句,就按照“条件表达式1”指定的条件进行查询;如果没有WHERE子句,就查询所有记录。 如果有GROUP BY子句,就按照“属性名1”指定的字段进行分组;如果GROUP BY子句后面带着HAVING关键字,那么只有满足“条件表达式2”中指定的条件的记录才能够输出。GROUP BY子句通常和COUNT()、SUM()等聚合函数一起使用。 如果有ORDER BY子句,就按照“属性名2”指定的字段进行排序。排序方式由ASC或DESC参数指定。默认的排序方式为ASC。 二、在表上查询数据 2.1、查询所有字段 [sql] view plain copy select * from STUDENT; 2.2、按条件查询 (1) 比较运算符 > , < ,= , != (),>= , 13; in(v1,v2..vn) ,符合v1,v2,,,vn才能被查出 IN关键字可以判断某个字段的值是否在指定的集合中。如果字段的值在集合中,则满足查询条件,该纪录将被查询出来。如果不在集合中,则不满足查询条件。其语法规则如下:[ NOT ] IN ( 元素1, 元素2, …, 元素n ) [sql] view plain copy select * from STUDENT where STU_AGE in(11,12); between v1 and v2 在v1至v2之间(包含v1,v2) BETWEEN AND关键字可以判读某个字段的值是否在指定的范围内。如果字段的值在指定范围内,则满足查询条件,该纪录将被查询出来。如果不在指定范围内,则不满足查询条件。其语法规则如下: [ NOT ] BETWEEN 取值1 AND 取值2 [sql] view plain copy select * from STUDENT where STU_AGE between 13 and 15; (2)逻辑运算符 not ( ! ) 逻辑非 [sql] view plain copy select * from STUDENT where STU_AGE NOT IN(13,14,16); or ( || ) 逻辑或 OR关键字也可以用来联合多个条件进行查询,但是与AND关键字不同。使用OR关键字时,只要满足这几个查询条件的其中一个,这样的记录将会被查询出来。如果不满足这些查询条件中的任何一个,这样的记录将被排除掉。OR关键字的语法规则如下: 条件表达式1 OR 条件表达式2 [ …OR 条件表达式n ] 其中,OR可以用来连接两个条件表达式。而且,可以同时使用多个OR关键字,这样可以连接更多的条件表达式。 [sql] view plain copy select * from STUDENT where STU_ID2015; and ( && ) 逻辑与 AND关键字可以用来联合多个条件进行查询。使用AND关键字时,只有同时满足所有查询条件的记录会被查询出来。如果不满足这些查询条件的其中一个,这样的记录将被排除掉。AND关键字的语法规则如下: 条件表达式1 AND 条件表达式2 [ … AND 条件表达式n ] 其中,AND可以连接两个条件表达式。而且,可以同时使用多个AND关键字,这样可以连接更多的条件表达式。 (3)模糊查询 like 像 LIKE关键字可以匹配字符串是否相等。如果字段的值与指定的字符串相匹配,则满足查询条件,该纪录将被查询出来。如果与指定的字符串不匹配,则不满足查询条件。其语法规则如下:[ NOT ] LIKE '字符串' “NOT”可选参数,加上 NOT表示与指定的字符串不匹配时满足条件;“字符串”表示指定用来匹配的字符串,该字符串必须加引号或双引号。 通配符: % 任意字符 [sql] view plain copy select * from STUDENT where STU_NAME LIKE '%王'; 表示匹配任何以王结尾的 [sql] view plain copy select * from STUDENT where STU_NAME LIKE '阿%'; 表示匹配任何以阿开头的 _ 个字符 比如说插入 [sql] view plain copy insert into STUDENT values(2021,'天下无镜',14,'男'); 然后 [sql] view plain copy select * from STUDENT where STU_NAME LIKE '_下_'; 查询的结果为空 但是如果下后面加两个_符号 [sql] view plain copy select * from STUDENT where STU_NAME LIKE '_下__'; 查询结果不为空 “字符串”参数的值可以是一个完整的字符串,也可以是包含百分号(%)或者下划线(_)的通配字符。二者有很大区别 “%”可以代表任意长度的字符串,长度可以为0; “_”只能表示个字符。 如果要匹配姓张且名字只有两个字的人的记录,“张”字后面必须要有两个“_”符号。因为一个汉字是两个字符,而一个“_”符号只能代表一个字符。 (4)空值查询 IS NULL关键字可以用来判断字段的值是否为空值(NULL)。如果字段的值是空值,则满足查询条件,该记录将被查询出来。如果字段的值不是空值,则不满足查询条件。其语法规则如下: IS [ NOT ] NULL 其中,“NOT”是可选参数,加上NOT表示字段不是空值时满足条件。 IS NULL是一个整体,不能将IS换成”=”. 三、使用聚合函数查询数据 3.1、group by 分组 如下: [sql] view plain copy select * from STUDENT group by STU_SEX; 不加条件,那么就只取每个分组的第一条。 如果想看分组的内容,可以加groub_concat [sql] view plain copy select STU_SEX,group_concat(STU_NAME) from STUDENT group by STU_SEX; 3.2、一般情况下group需与统计函数(聚合函数)一起使用才有意义 先准备一些数据: [sql] view plain copy create table EMPLOYEES( EMP_NAME CHAR(10) NOT NULL, EMP_SALARY INT unsigned NOT NULL, EMP_DEP CHAR(10) NOT NULL ); insert into EMPLOYEES values('小王',5000,'销售部'); insert into EMPLOYEES values('阿小王',6000,'销售部'); insert into EMPLOYEES values('工是不',7000,'销售部'); insert into EMPLOYEES values('人人乐',3000,'资源部'); insert into EMPLOYEES values('满头大',4000,'资源部'); insert into EMPLOYEES values('天生一家',5500,'资源部'); insert into EMPLOYEES values('小花',14500,'资源部'); insert into EMPLOYEES values('大玉',15000,'研发部'); insert into EMPLOYEES values('条条',12000,'研发部'); insert into EMPLOYEES values('笨笨',13000,'研发部'); insert into EMPLOYEES values('我是天才',15000,'研发部'); insert into EMPLOYEES values('无语了',6000,'审计部'); insert into EMPLOYEES values('什么人',5000,'审计部'); insert into EMPLOYEES values('不知道',4000,'审计部'); mysql中的五种统计函数: (1)max:求最大值 求每个部门的最高工资: [sql] view plain copy select EMP_NAME,EMP_DEP,max(EMP_SALARY) from EMPLOYEES group by EMP_DEP; (2)min:求最小值 求每个部门的最仰工资: [sql] view plain copy select EMP_NAME,EMP_DEP,min(EMP_SALARY) from EMPLOYEES group by EMP_DEP; (3)sum:求总数和 求每个部门的工资总和: [sql] view plain copy select EMP_DEP,sum(EMP_SALARY) from EMPLOYEES group by EMP_DEP (4)avg:求平均值 求每个部门的工资平均值 [sql] view plain copy select EMP_DEP,avg(EMP_SALARY) from EMPLOYEES group by EMP_DEP; (5)count:求总行数 求每个部门工资大于一定金额的人数 [sql] view plain copy select EMP_DEP,count(*) from EMPLOYEES where EMP_SALARY>=500 group by EMP_DEP; 3.3、带条件的groub by 字段 having,利用HAVING语句过滤分组数据 having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚组函数,使用having 条件显示特定的组,也可以使用多个分组标准进行分组。 having 子句被限制子已经在SELECT语句中定义的列和聚合表达式上。通常,你需要通过在HAVING子句中重复聚合函数表达式来引用聚合值,就如你在SELECT语句中做的那样。 [sql] view plain copy select EMP_DEP,avg(EMP_SALARY),group_concat(EMP_NAME)from EMPLOYEES group by EMP_DEP HAVING avg(EMP_SALARY) >=6000; 查找平均工资大于6000的部门,并把部门里的人全部列出来 四、多表上联合查询 多表上联合查询分为内连接查询和外连接查询 (1)隐式内连接查询 [sql] view plain copy select STUDENT.STU_ID,STUDENT.STU_NAME,STUDENT.STU_AGE,STUDENT.STU_SEX,GRADE.STU_SCORE from STUDENT,GRADE WHERE STUDENT.STU_ID=GRADE.STU_ID AND GRADE.STU_SCORE >=90; 查找大于90分的学生信息: (2)显式内连接查询 [sql] view plain copy select STUDENT.STU_ID,STUDENT.STU_NAME,STUDENT.STU_AGE,STUDENT.STU_SEX,GRADE.STU_SCORE from STUDENT inner join GRADE on STUDENT.STU_ID=GRADE.STU_ID AND GRADE.STU_SCORE >=90; 用法:select .... from 表1 inner join 表2 on 条件表达式 (3)外连接查询 left join.左连接查询。 用法 :select .... from 表1 left join 表2 on 条件表达式 意思是表1查出来的数据不能为null,但是其对应表2的数据可以为null [sql] view plain copy select STUDENT.STU_ID,STUDENT.STU_NAME,STUDENT.STU_AGE,STUDENT.STU_SEX,GRADE.STU_SCORE from STUDENT left join GRADE on STUDENT.STU_ID=GRADE.STU_ID; right join就是相反的了,用法相同 用left join的时候,left join操作符左侧表里的信息都会被查询出来,右侧表里没有的记录会填空(NULL).right join亦然;inner join的时候则只有条件合适的才会显示出来 full join() 完整外部联接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据 值。 仅当至少有一个同属于两表的行符合联接条件时,内联接才返回行。内联接消除与另一个表中的任何行不匹配的行。而外联接会返回 FROM 子句中提到的至少一个表或 视图的所有行,只要这些行符合任何 WHERE 或 HAVING 搜索条件。将检索通过左向外联接引用的左表的所有行,以及通过右向外联接引用的右表的所有行。完整外 部联接中两个表的所有行都将返回。 五、子查询 以一个查询select的结果作为另一个查询的条件 语法:select * from 表1 wher 条件1(select ..from 表2 where 条件2) 1、与In结合 [sql] view plain copy select * from STUDENT where STU_ID IN(select STU_ID from GRADE where STU_SCORE>85); 查找大于85分的学生信息 2、与EXISTS结合 EXISTS和NOT EXISTS操作符只测试某个子查询是否返回了数据行。如果是,EXISTS将是true,NOT EXISTS将是false。 [sql] view plain copy select * from STUDENT where EXISTS (select STU_ID from GRADE where STU_SCORE>=100); 如果有学生成绩大于100,才查询所有的学生信息 3、ALL、ANY和SOME子查询 any和all的操作符常见用法是结合一个相对比较操作符对一个数据列子查询的结果进行测试。它们测试比较值是否与子查询所返回的全部或一部分值匹配。比方说,如果比较值小于或等于子查询所返回的每一个值,<=all将是true,只要比较值小于或等于子查询所返回的任何一个值,<=any将是true。some是any的一个同义词。 [sql] view plain copy select STU_ID from GRADE where STU_SCORE = any (select STU_ID from GRADE where STU_SCORE 80 order by STU_SCORE; 默认是按升序的, 也可以这么写 [sql] view plain copy select * from GRADE where STU_SCORE >80 order by STU_SCORE ASC; 结果如下: 如果想换成降序的: [sql] view plain copy select * from GRADE where STU_SCORE >80 order by STU_SCORE desc; 7.2、limit limit [offset,] N offset 偏移量,可选,不写则相当于limit 0,N N 取出条目 取分数最高的前5条 [sql] view plain copy select * from GRADE order by STU_SCORE desc limit 5; 取分数最低的前5条 [sql] view plain copy select * from GRADE order by STU_SCORE asc limit 5; 取分数排名在10-15之间的5条 [sql] view plain copy select * from GRADE order by STU_SCORE desc limit 10,5 八、为表和字段取别名 使用AS来命名列 [sql] view plain copy select STU_ID as '学号',STU_SCORE as '分数' from GRADE; 当表的名称特别长时,在查询中直接使用表名很不方便。这时可以为表取一个别名。用这个别名来代替表的名称。 MySQL中为表取别名的基本形式如下: 表名 表的别名 [sql] view plain copy select S.STU_ID,S.STU_NAME,S.STU_AGE,S.STU_SEX,G.STU_SCORE from STUDENT S,GRADE G WHERE S.STU_ID=G.STU_ID AND G.STU_SCORE >=90; 九、使用正则表达式查询 正则表达式是用某种模式去匹配一类字符串的一个方式。例如,使用正则表达式可以查询出包含A、B、C其中任一字母的字符串。正则表达式的查询能力比通配字符的查询能力更强大,而且更加的灵活。正则表达式可以应用于非常复杂查询。 MySQL中,使用REGEXP关键字来匹配查询正则表达式。其基本形式如下: 属性名 REGEXP '匹配方式' 在使用前先插入一些数据: [sql] view plain copy insert into STUDENT values(2022,'12wef',13,'男'); insert into STUDENT values(2023,'faf_23',13,'男'); insert into STUDENT values(2024,'fafa',13,'女'); insert into STUDENT values(2025,'ooop',14,'男'); insert into STUDENT values(2026,'23oop',14,'男'); insert into STUDENT values(2027,'woop89',14,'男'); insert into STUDENT values(2028,'abcdd',11,'男'); (1)使用字符“^”可以匹配以特定字符或字符串开头的记录。 查询所有以阿头的 [sql] view plain copy select * from STUDENT where STU_NAME REGEXP '^阿'; 以数字开头 [sql] view plain copy select * from STUDENT where STU_NAME REGEXP '^[0-9]'; (2)使用字符“$”可以匹配以特定字符或字符串结尾的记录 以数字结尾 [sql] view plain copy select * from STUDENT where STU_NAME REGEXP '[0-9]$'; (3)用正则表达式来查询时,可以用“.”来替代字符串中的任意一个字符。 [sql] view plain copy select * from STUDENT where STU_NAME REGEXP '^w....[0-9]$'; 以w开头,以数字结束,中间有4个 (4)使用方括号([])可以将需要查询字符组成一个字符集。只要记录中包含方括号中的任意字符,该记录将会被查询出来。 例如,通过“[abc]”可以查询包含a、b、c这三个字母中任何一个的记录。 使用方括号可以指定集合的区间。 “[a-z]”表示从a-z的所有字母; “[0-9]”表示从0-9的所有数字; “[a-z0-9]”表示包含所有的小写字母和数字。 “[a-zA-Z]”表示匹配所有字母。 [sql] view plain copy select * from STUDENT where STU_NAME REGEXP '[0-9a-z]'; 查询所有包含有数字和小写字母的 使用“[^字符集合]”可以匹配指定字符以外的字符 (5){}表示出现的次数 正则表达式中,“字符串{M}”表示字符串连续出现M次;“字符串{M,N}”表示字符串联连续出现至少M次,最多N次。例如,“ab{2}”表示字符串“ab”连续出现两次。“ab{2,4}”表示字符串“ab”连续出现至少两次,最多四次。 o出现2次 [sql] view plain copy select * from STUDENT where STU_NAME REGEXP 'o{2}'; (6)+表示到少出现一次 fa至少出现一次 [sql] view plain copy select * from STUDENT where STU_NAME REGEXP '(fa)+'; 注意: 正则表达式可以匹配字符串。当表中的记录包含这个字符串时,就可以将该记录查询出来。如果指定多个字符串时,需要用符号“|”隔开。只要匹配这些字符串中的任意一个即可。每个字符串与”|”之间不能有空格。因为,查询过程中,数据库系统会将空格也当作一个字符。这样就查询不出想要的结果。 正则表达式中,“*”和“+”都可以匹配多个该符号之前的字符。但是,“+”至少表示一个字符,而“*”可以表示零个字符。
Ø 常用查询 MySQL结束符是“;”结束。 1、 显示所有数据库 show databases; 2、 删除数据库 drop database dbName; 3、 创建数据库 create database [if not exists] dbName; 中括号部分可选的,判断该数据不存在就创建 4、 切换、使用指定数据库 use dbName; 5、 显示当前使用数据库所有的表对象 show tables; 6、 显示表结构describe(desc) desc tableName; 7、 创建一张表 create table user ( --int 整型 uId int, --小数 uPrice decimal, --普通长度文本,default设置默认值 uName varchar(255) default ‘zhangsan’, --超长文本 uRemark text, --图片 uPhoto blob, --日期 uBirthday datetime ); 8、 子查询建表方法 部分列名匹配模式: create table userInfo ( name varchar(20), sex char ) as select name, sex from user; 上面的列名和子查询的列名以及类型要对应 全部列名模式: create table userInfo as select * from user; 直接将整个表的类型和数据备份到新表userInfo中 9、 添加表字段 添加列 alter table user add tel varchar(11) default ‘02012345678’; 添加多列 alter table user add ( photo blob, birthday date ); 上面就同时增加了多列字段 10、 修改表字段 修改tel列 alter table user modify tel varchar(15) default ‘02087654321’; 修改tel列的位置,在第一列显示 alter table user modify tel varchar(15) default '02087654321' first; 修改tel列的位置,在指定列之后显示 alter table user modify tel varchar(15) default '02087654321' after age; 注意:alter modify不支持一次修改多个列,但是Oracle支持多列修改 但是MySQL可以通过多个modify的方式完成: alter table user modify tel varchar(15) default '02087654321' first, modify name varchar(20) after tel; 11、 删除指定字段 alter table user drop photo; 12、 重命名表数据 表重命名 alter table user rename to users; 字段重命名 alter table users change name u_name varchar(10); alter table users change sex u_sex varchar(10) after u_name; 如果需要改变列名建议使用change,如果需要改变数据类型和显示位置可以使用modify 13、 删除表 drop table users; drop删除表会删除表结构,表对象将不存在数据中;数据也不会存在;表内的对象也不存在,如:索引、视图、约束; truncate删除表 truncate都被当成DDL出来,truncate的作用就是删除该表里的全部数据,保留表结构。相当于DDL中的delete语句, 但是truncate比delete语句的速度要快得多。但是truncate不能带条件删除指定数据,只会删除所有的数据。如果删除的表有外键, 删除的速度类似于delete。但新版本的MySQL中truncate的速度比delete速度快。 Ø 约束 MySQL中约束保存在information_schema数据库的table_constraints中,可以通过该表查询约束信息; 约束主要完成对数据的检验,保证数据库数据的完整性;如果有相互依赖数据,保证该数据不被删除。 常用五类约束: not null:非空约束,指定某列不为空 unique: 唯一约束,指定某列和几列组合的数据不能重复 primary key:主键约束,指定某列的数据不能重复、唯一 foreign key:外键,指定该列记录属于主表中的一条记录,参照另一条数据 check:检查,指定一个表达式,用于检验指定数据 MySQL不支持check约束,但可以使用check约束,而没有任何效果; 根据约束数据列限制,约束可分为: 列约束:每个约束只约束一列 多列约束:每个约束约束多列数据 MySQL中约束保存在information_schema数据库的table_constraints中,可以通过该表查询约束信息; 1、 not null约束 非空约束用于确保当前列的值不为空值,非空约束只能出现在表对象的列上。 Null类型特征: 所有的类型的值都可以是null,包括int、float等数据类型 空字符串“”是不等于null,0也不等于null create table temp( id int not null, name varchar(255) not null default ‘abc’, sex char null ) 上面的table加上了非空约束,也可以用alter来修改或增加非空约束 增加非空约束 alter table temp modify sex varchar(2) not null; 取消非空约束 alter table temp modify sex varchar(2) null; 取消非空约束,增加默认值 alter table temp modify sex varchar(2) default ‘abc’ null; 2、 unique 唯一约束是指定table的列或列组合不能重复,保证数据的唯一性。虽然唯一约束不允许出现重复的值,但是可以为多个null 同一个表可以有多个唯一约束,多个列组合的约束。在创建唯一约束的时候,如果不给唯一约束名称,就默认和列名相同。 唯一约束不仅可以在一个表内创建,而且可以同时多表创建组合唯一约束。 MySQL会给唯一约束的列上默认创建一个唯一索引; create table temp ( id int not null, name varchar(25), password varchar(16), --使用表级约束语法, constraint uk_name_pwd unique(name, password) ); 表示用户名和密码组合不能重复 添加唯一约束 alter table temp add unique(name, password); alter table temp modify name varchar(25) unique; 删除约束 alter table temp drop index name; 3、 primary key 主键约束相当于唯一约束+非空约束的组合,主键约束列不允许重复,也不允许出现空值;如果的多列组合的主键约束, 那么这些列都不允许为空值,并且组合的值不允许重复。 每个表最多只允许一个主键,建立主键约束可以在列级别创建,也可以在表级别上创建。MySQL的主键名总是PRIMARY, 当创建主键约束时,系统默认会在所在的列和列组合上建立对应的唯一索引。 列模式: create table temp( /*主键约束*/ id int primary key, name varchar(25) ); create table temp2( id int not null, name varchar(25), pwd varchar(15), constraint pk_temp_id primary key(id) ); 组合模式: create table temp2( id int not null, name varchar(25), pwd varchar(15), constraint pk_temp_id primary key(name, pwd) ); alter删除主键约束 alter table temp drop primary key; alter添加主键 alter table temp add primary key(name, pwd); alter修改列为主键 alter table temp modify id int primary key; 设置主键自增 create table temp( id int auto_increment primary key, name varchar(20), pwd varchar(16) ); auto_increment自增模式,设置自增后在插入数据的时候就不需要给该列插入值了。 4、 foreign key 约束 外键约束是保证一个或两个表之间的参照完整性,外键是构建于一个表的两个字段或是两个表的两个字段之间的参照关系。 也就是说从表的外键值必须在主表中能找到或者为空。 当主表的记录被从表参照时,主表的记录将不允许删除,如果要删除数据,需要先删除从表中依赖该记录的数据, 然后才可以删除主表的数据。还有一种就是级联删除子表数据。 注意:外键约束的参照列,在主表中引用的只能是主键或唯一键约束的列,假定引用的主表列不是唯一的记录, 那么从表引用的数据就不确定记录的位置。同一个表可以有多个外键约束。 创建外键约束: 主表 create table classes( id int auto_increment primary key, name varchar(20) ); 从表 create table student( id int auto_increment, name varchar(22), constraint pk_id primary key(id), classes_id int references classes(id) ); 通常先建主表,然后再建从表,这样从表的参照引用的表才存在。 表级别创建外键约束: create table student( id int auto_increment primary key, name varchar(25), classes_id int, foreign key(classes_id) references classes(id) ); 上面的创建外键的方法没有指定约束名称,系统会默认给外键约束分配外键约束名称,命名为student_ibfk_n, 其中student是表名,n是当前约束从1开始的整数。 指定约束名称: create table student( id int auto_increment primary key, name varchar(25), classes_id int, /*指定约束名称*/ constraint fk_classes_id foreign key(classes_id) references classes(id) ); 多列外键组合,必须用表级别约束语法: create table classes( id int, name varchar(20), number int, primary key(name, number) ); create table student( id int auto_increment primary key, name varchar(20), classes_name varchar(20), classes_number int, /*表级别联合外键*/ foreign key(classes_name, classes_number) references classes(name, number) ); 删除外键约束: alter table student drop foreign key student_ibfk_1; alter table student drop foreign key fk_student_id; 增加外键约束 alter table student add foreign key(classes_name, classes_number) referencesclasses(name, number); 自引用、自关联(递归表、树状表) create table tree( id int auto_increment primary key, name varchar(50), parent_id int, foreign key(parent_id) references tree(id) ); 级联删除:删除主表的数据时,关联的从表数据也删除,则需要在建立外键约束的后面增加on deletecascade 或on delete set null,前者是级联删除,后者是将从表的关联列的值设置为null。 create table student( id int auto_increment primary key, name varchar(20), classes_name varchar(20), classes_number int, /*表级别联合外键*/ foreign key(classes_name, classes_number) references classes(name, number) on deletecascade ); 5、 check约束 MySQL可以使用check约束,但check约束对数据验证没有任何作用。 create table temp( id int auto_increment, name varchar(20), age int, primary key(id), /*check约束*/ check(age > 20) ); 上面check约束要求age必须大于0,但没有任何作用。但是创建table的时候没有任何错误或警告。 Ø 索引 索引是存放在模式(schema)中的一个数据库对象,索引的作用就是提高对表的检索查询速度, 索引是通过快速访问的方法来进行快速定位数据,从而减少了对磁盘的读写操作。 索引是数据库的一个对象,它不能独立存在,必须对某个表对象进行依赖。 提示:索引保存在information_schema数据库里的STATISTICS表中。 创建索引方式: 自动:当表上定义主键约束、唯一、外键约束时,该表会被系统自动添加上索引。 手动:手动在相关表或列上增加索引,提高查询速度。 删除索引方式: 自动:当表对象被删除时,该表上的索引自动被删除 手动:手动删除指定表对象的相关列上的索引 索引类似于书籍的目录,可以快速定位到相关的数据,一个表可以有多个索引。 创建索引: create index idx_temp_name on temp(name); 组合索引: create index idx_temp_name$pwd on temp(name, pwd); 删除索引: drop index idx_temp_name on temp; Ø 视图 视图就是一个表或多个表的查询结果,它是一张虚拟的表,因为它并不能存储数据。 视图的作用、优点: 限制对数据的访问 让复杂查询变得简 提供数据的独立性 可以完成对相同数据的不同显示 创建、修改视图 create or replace view view_temp as select name, age from temp; 通常我们并不对视图的数据做修改操作,因为视图是一张虚拟的表,它并不存储实际数据。如果想让视图不被修改,可以用with check option来完成限制。 create or replace view view_temp as select * from temp with check option; 修改视图: alter view view_temp as select id, name from temp; 删除视图: drop view view_temp; 显示创建语法: show create view v_temp; Ø DML语句 DML主要针对数据库表对象的数据而言的,一般DML完成: 插入新数据 修改已添加的数据 删除不需要的数据 1、 insert into 插入语句 insert into temp values(null, ‘jack’, 25); 主键自增可以不插入,所以用null代替 指定列 insert into temp(name, age) values(‘jack’, 22); 在表面后面带括号,括号中写列名,values中写指定列名的值即可。当省略列名就表示插入全部数据, 注意插入值的顺序和列的顺序需要保持一致。 Set方式插入,也可以指定列 insert into temp set id = 7, name = 'jason'; MySQL中外键的table的外键引用列可以插入数据可以为null,不参照主表的数据。 使用子查询插入数据 insert into temp(name) select name from classes; 多行插入 insert into temp values(null, ‘jack’, 22), (null, ‘jackson’ 23); 2、 update 修改语句 update主要完成对数据的修改操作,可以修改一条或多条数据。修改多条或指定条件的数据,需要用where条件来完成。 修改所有数据 update temp set name = ‘jack2’; 所有的数据的name会被修改,如果修改多列用“,”分开 update temp set name = ‘jack’, age = 22; 修改指定条件的记录需要用where update temp set name = ‘jack’ where age > 22; 3、 delete 删除语句 删除table中的数据,可以删除所有,带条件可以删除指定的记录。 删除所有数据 delete from temp; 删除指定条件数据 delete from temp where age > 20; Ø select 查询、function 函数 select查询语句用得最广泛、功能也最丰富。可以完成条记录、多条记录、表、多表、子查询等。 1、 查询某张表所有数据 select * from temp; *代表所有列,temp代表表名,不带条件就查询所有数据 2、 查询指定列和条件的数据 select name, age from temp where age = 22; 查询name和age这两列,age 等于22的数据。 3、 对查询的数据进行运算操作 select age + 2, age / 2, age – 2, age * 2 from temp where age – 2 > 22; 4、 concat函数,字符串连接 select concat(name, ‘-eco’) from temp; concat和null进行连接,会导致连接后的数据成为null 5、 as 对列重命名 select name as ‘名称’ from temp; as也可以省略不写,效果一样 如果重命名的列名出现特殊字符,如“‘”引号,那就需要用双引号引在外面 select name as “名’称” from temp; 6、 也可以给table去别名 select t.name Name from temp as t; 7、 查询常量 类似于SQL Server select 5 + 2; select concat('a', 'bbb'); 8、 distinct 去掉重复数据 select distinct id from temp; 多列将是组合的重复数据 select distinct id, age from temp; 9、 where 条件查询 大于>、大于等于>=、小于<、小于等于<=、等于=、不等于<> 都可以出现在where语句中 select * from t where a > 2 or a >= 3 or a < 5 or a <= 6 or a = 7 or a <> 0; 10、 and 并且 select * from temp where age > 20 and name = ‘jack’; 查询名称等于jack并且年龄大于20的 11、 or 或者 满足一个即可 select * from tmep where name = ‘jack’ or name = ‘jackson’; 12、 between v and v2 大于等于v且小于等于v2 select * form temp where age between 20 and 25; 13、 in 查询 可以多个条件 类似于or select * from temp where id in (1, 2, 3); 查询id在括号中出现的数据 14、 like 模糊查询 查询name以j开头的 select * from temp where name like ‘j%’; 查询name包含k的 select * from temp where name like ‘%k%’; escape转义 select * from temp where name like ‘/_%’ escape ‘/’; 指定/为转义字符,上面的就可以查询name中包含“_”的数据 15、 is null、is not null 查询为null的数据 select * from temp where name is null; 查询不为null的数据 select * from temp where name is not null; 16、 not select * from temp where not (age > 20); 取小于等于20的数据 select * from temp where id not in(1, 2); 17、 order by 排序,有desc、asc升序、降序 select * from temp order by id; 默认desc排序 select * from temp order by id asc; 多列组合 select * from temp order by id, age; Ø function 函数 函数的作用比较大,一般多用在select查询语句和where条件语句之后。按照函数返回的结果, 可以分为:多行函数和行函数;所谓的行函数就是将每条数据进行独立的计算,然后每条数据得到一条结果。 如:字符串函数;而多行函数,就是多条记录同时计算,得到最终只有一条结果记录。如:sum、avg等 多行函数也称为聚集函数、分组函数,主要用于完成一些统计功能。MySQL行函数有如下特征: 行函数的参数可以是变量、常量或数据列。行函数可以接受多个参数,但返回一个值。 行函数就是它会对每一行独起作用,每一行(可能包含多个参数)返回一个结果。 行函数可以改变参数的数据类型。行函数支持嵌套使用:内层函数的返回值是外层函数的参数。 行函数可以分为: 类型转换函数; 位函数; 流程控制语句; 加密解密函数; 信息函数 行函数 1、 char_length字符长度 select char_length(tel) from user; 2、 sin函数 select sin(age) from user; select sin(1.57); 3、 添加日期函数 select date_add('2010-06-21', interval 2 month); interval是一个关键字,2 month是2个月的意思,2是数值,month是位 select addDate('2011-05-28', 2); 在前面的日期上加上后面的天数 4、 获取当前系统时间、日期 select curdate(); select curtime(); 5、 加密函数 select md5('zhangsan'); 6、 Null 处理函数 select ifnull(birthday, 'is null birthday') from user; 如果birthday为null,就返回后面的字符串 select nullif(age, 245) from user; 如果age等于245就返回null,不等就返回age select isnull(birthday) from user; 判断birthday是否为null select if(isnull(birthday), 'birthday is null', 'birthday not is null') from user; 如果birthday为null或是0就返回birthday is null,否则就返回birthday not is null;类似于三目运算符 7、 case 流程函数 case函数是一个流程控制函数,可以接受多个参数,但最终只会返回一个结果。 select name, age, (case sex when 1 then '男' when 0 then '女' else '火星人' end ) sex from user; 组函数 组函数就是多行函数,组函数是完成一行或多行结果集的运算,最后返回一个结果,而不是每条记录返回一个结果。 1、 avg平均值运算 select avg(age) from user; select avg(distinct age) from user; 2、 count 记录条数统计 select count(*), count(age), count(distinct age) from user; 3、 max 最大值 select max(age), max(distinct age) from user; 4、 min 最小值 select min(age), min(distinct age) from user; 5、 sum 求和、聚和 select sum(age), sum(distinct age) from user; select sum(ifnull(age, 0)) from user; 6、 group by 分组 select count(*), sex from user group by sex; select count(*) from user group by age; select * from user group by sex, age; 7、 having进行条件过滤 不能在where子句中过滤组,where子句仅用于过滤行。过滤group by需要having 不能在where子句中用组函数,having中才能用组函数 select count(*) from user group by sex having sex <> 2; Ø 多表查询和子查询 数据库的查询功能最为丰富,很多时候需要用到查询完成一些事物,而且不是纯的对一个表进行操作。而是对多个表进行联合查询, MySQL中多表连接查询有两种规范,较早的SQL92规范支持,如下几种表连接查询: 等值连接 非等值连接 外连接 广义笛卡尔积 SQL99规则提供了可读性更好的多表连接语法,并提供了更多类型的连接查询,SQL99支持如下几种多表连接查询: 交叉连接 自然连接 使用using子句的连接 使用on子句连接 全部连接或者左右外连接 SQL92的连接查询 SQL92的连接查询语法比较简,多将多个table放置在from关键字之后,多个table用“,”隔开; 连接的条件放在where条件之后,与查询条件直接用and逻辑运算符进行连接。如果条件中使用的是相等, 则称为等值连接,相反则称为非等值,如果没有任何条件则称为广义笛卡尔积。 广义笛卡尔积:select s.*, c.* from student s, classes c; 等值:select s.*, c.* from student s, classes c where s.cid = c.id; 非等值:select s.*, c.* from student s, classes c where s.cid <> c.id; select s.*, c.name classes from classes c, student s where c.id = s.classes_id ands.name is not null; SQL99连接查询 1、交叉连接cross join,类似于SQL92的笛卡尔积查询,无需条件。如: select s.*, c.name from student s cross join classes c; 2、自然连接 natural join查询,无需条件,默认条件是将2个table中的相同字段作为连接条件,如果没有相同字段,查询的结果就是空。 select s.*, c.name from student s natural join classes c; 3、using子句连接查询:using的子句可以是一列或多列,显示的指定两个表中同名列作为连接条件。 如果用natural join的连接查询,会把所有的相同字段作为连接查询。而using可以指定相同列及个数。 select s.*, c.name from student s join classes c using(id); 4、 join … on连接查询,查询条件在on中完成,每个on语句只能指定一个条件。 select s.*, c.name from student s join classes c on s.classes_id = c.id; 5、 左右外连接:3种外连接,left [outer] join、right [outer] join,连接条件都是通过用on子句来指定,条件可以等值、非等值。 select s.*, c.name from student s left join classes c on s.classes_id = c.id; select s.*, c.name from student s right join classes c on s.classes_id = c.id; 子查询 子查询就是指在查询语句中嵌套另一个查询,子查询可以支持多层嵌套。子查询可以出现在2个位置: from关键字之后,被当做一个表来进行查询,这种用法被称为行内视图,因为该子查询的实质就是一个临时视图 出现在where条件之后作为过滤条件的值 子查询注意点: 子查询用括号括起来,特别情况下需要起一个临时名称 子查询当做临时表时(在from之后的子查询),可以为该子查询起别名,尤其是要作为前缀来限定数据列名时 子查询用作过滤条件时,将子查询放在比较运算符的右边,提供可读性 子查询作为过滤条件时,行子查询使用行运算符,多行子查询用多行运算符 将from后面的子查询当做一个table来用: select * from (select id, name from classes) s where s.id in (1, 2); 当做条件来用: select * from student s where s.classes_id in (select id from classes); select * from student s where s.classes_id = any (select id from classes); select * from student s where s.classes_id > any (select id from classes); Ø 操作符和函数 1、 boolean只判断 select 1 is true, 0 is false, null is unknown; select 1 is not unknown, 0 is not unknown, null is not unknown; 2、 coalesce函数,返回第一个非null的值 select coalesce(null, 1); select coalesce(1, 1); select coalesce(null, 1); select coalesce(null, null); 3、 当有2个或多个参数时,返回最大的那个参数值 select greatest(2, 3); select greatest(2, 3, 1, 9, 55, 23); select greatest('D', 'A', 'B'); 4、 Least函数,返回最小值,如果有null就返回null值 select least(2, 0); select least(2, 0, null); select least(2, 10, 22.2, 35.1, 1.1); 5、 控制流函数 select case 1 when 1 then 'is 1' when 2 then 'is 2' else 'none' end; select case when 1 > 2 then 'yes' else 'no' end; 6、 ascii字符串函数 select ascii('A'); select ascii('1'); 7、 二进制函数 select bin(22); 8、 返回二进制字符串长度 select bit_length(11); 9、 char将值转换成字符,小数取整四舍五入 select char(65); select char(65.4); select char(65.5); select char(65.6); select char(65, 66, 67.4, 68.5, 69.6, '55.5', '97.3'); 10、 using改变字符集 select charset(char(0*65)), charset(char(0*65 using utf8)); 11、 得到字符长度char_length,character_length select char_length('abc'); select character_length('eft'); 12、 compress压缩字符串、uncompress解压缩 select compress('abcedf'); select uncompress(compress('abcedf')); 13、 concat_ws分隔字符串 select concat_ws('#', 'first', 'second', 'last'); select concat_ws('#', 'first', 'second', null, 'last'); Ø 事务处理 动作 开始事务:start transaction 提交事务:commit 回滚事务:rollback 设置自动提交:set autocommit 1 | 0 atuoCommit系统默认是1立即提交模式;如果要手动控制事务,需要设置set autoCommit 0; 这样我们就可以用commit、rollback来控制事务了。 在一段语句块中禁用autocommit 而不是set autocommit start transaction; select @result := avg(age) from temp; update temp set age = @result where id = 2; select * from temp where id = 2;//值被改变 rollback;//回滚 select * from temp where id = 2;//变回来了 在此期间只有遇到commit、rollback,start Transaction的禁用autocommit才会结束。然后就恢复到原来的autocommit模式; 不能回滚的语句 有些语句不能被回滚。通常,这些语句包括数据定义语言(DDL)语句,比如创建或取消数据库的语句, 和创建、取消或更改表或存储的子程序的语句。 您在设计事务时,不应包含这类语句。如果您在事务的前部中发布了一个不能被回滚的语句, 则后部的其它语句会发生错误,在这些情况下,通过发布ROLLBACK语句不能 回滚事务的全部效果。 一些操作也会隐式的提交事务 如alter、create、drop、rename table、lock table、set autocommit、starttransaction、truncate table 等等, 在事务中出现这些语句也会提交事务的 事务不能嵌套事务 事务的保存点 Savepoint pointName/Rollback to savepoint pointName 一个事务可以设置多个保存点,rollback可以回滚到指定的保存点,恢复保存点后面的操作。 如果有后面的保存点和前面的同名,则删除前面的保存点。 Release savepoint会删除一个保存点,如果在一段事务中执行commit或rollback,则事务结束,所以保存点删除。 Set Transaction设计数据库隔离级别 SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL { READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE } 本语句用于设置事务隔离等级,用于下一个事务,或者用于当前会话。 在默认情况下,SET TRANSACTION会为下一个事务(还未开始)设置隔离等级。 如果您使用GLOBAL关键词,则语句会设置全局性的默认事务等级, 用于从该点以后创建的所有新连接。原有的连接不受影响。使用SESSION关键测可以设置默认事务等级, 用于对当前连接执行的所有将来事务。 默认的等级是REPEATABLE READ全局隔离等级。 Ø 注释 select 1+1; # 行注释 select 1+1; -- 行注释 select 1 /* 多行注释 */ + 1; Ø 基本数据类型操作 字符串 select 'hello', '"hello"', '""hello""', 'hel''lo', '/'hello'; select "hello", "'hello'", "''hello''", "hel""lo", "/"hello"; /n换行 select 'This/nIs/nFour/nLines'; /转义 select 'hello / world!'; select 'hello /world!'; select 'hello // world!'; select 'hello /' world!'; Ø 设置数据库mode模式 SET sql_mode='ANSI_QUOTES'; create table t(a int); create table "tt"(a int); create table "t""t"(a int); craate talbe tab("a""b" int); Ø 用户变量 set @num1 = 0, @num2 = 2, @result = 0; select @result := (@num1 := 5) + @num2 := 3, @num1, @num2, @result; Ø 存储过程 创建存储过程: delimiter // create procedure get(out result int) begin select max(age) into result from temp; end// 调用存储过程: call get(@temp); 查询结果: select @temp; 删除存储过程: drop procedure get; 查看存储过程创建语句: show create procedure get; select…into 可以完成行记录的赋值: create procedure getRecord(sid int) begin declare v_name varchar(20) default 'jason'; declare v_age int; declare v_sex bit; select name, age, sex into v_name, v_age, v_sex from temp where id = sid; select v_name, v_age, v_sex; end; call getRecord(1); Ø 函数 函数类似于存储过程,只是调用方式不同 例如:select max(age) from temp; 创建函数: create function addAge(age int) returns int return age + 5; 使用函数: select addAge(age) from temp; 删除函数: drop function if exists addAge; drop function addAge; 显示创建语法: show create function addAge; Ø 游标 声明游标:declare cur_Name cursor for select name from temp; 打开游标:open cur_Name; Fetch游标:fetch cur_Name into @temp; 关闭游标:close cur_Name; 示例: CREATE PROCEDURE cur_show() BEGIN DECLARE done INT DEFAULT 0; DECLARE v_id, v_age INT; DECLARE v_name varchar(20); DECLARE cur_temp CURSOR FOR SELECT id, name, age FROM temp; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; OPEN cur_temp; REPEAT FETCH cur_temp INTO v_id, v_name, v_age; IF NOT done THEN IF isnull(v_name) THEN update temp set name = concat('test-json', v_id) where id = v_id; ELSEIF isnull(v_age) THEN update temp set age = 22 where id = v_id; END IF; END IF; UNTIL done END REPEAT; CLOSE cur_temp; END Ø 触发器 触发器分为insert、update、delete三种触发器事件类型 还有after、before触发时间 创建触发器: create trigger trg_temp_ins before insert on temp for each row begin insert into temp_log values(NEW.id, NEW.name); end// 删除触发器: drop trigger trg_temp_ins

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值