MySQL-连接查询

连接查询
内连接查询
JOIN/CROSS JOIN/INNER JOIN
通过ON连接
select u.id,u.username,u.email,u.sex,p.proName,COUNT(*) as TOTAL
from provinces AS p
JOIN cms_user AS  u
ON u.proId=p.id
where u.sex='男'
GROUP BY p.proName
HAVING count(*)>=1
ORDER BY u.id ASC;
多表的时候直接加JOIN ON

外连接
左外连接 left join
右外连接 right join
符合条件的查找出来,不符合条件的以NULL替代
select u.id,u.username,COUNT(*) as TOTAL
from provinces AS p
LEFT JOIN cms_user AS  u
ON u.proId=p.id

联合查询
union 去掉重复的
union all 简单合并
select username from cms_user union select username from cms_admin;

子查询
select id,username from employee where depId not in (select id from department)
使用符号=,>,<,>=,<=,<>,!=,<=>
select id,username from student where score >=(select level from schoship where id=1);
exist/not exist
select id,username from employee where exists(select * from department where id =1)
运算符   ANY   SOME   ALL
>,>=     最小  最小   最大
<,<=     最大  最大   最小
=        任意  任意
<>,!=                 任意

将查询结果写入数据库
create table test2(
id tinyint unsigned auto_increment key,
num tinyint unsigned
)select id,score from student;
字段名称相同时才能赋值。

insert test1(id,num) select id,score from student


正则表达式查询
关键字 regexp'匹配方式'
常用匹配方式
^ 匹配字符开始部分
$ 匹配字符串结尾的部分
. 代表任意一个字符,包括回车和换行
[]匹配字符集合中的任何一个字符
s1|s2|s3 匹配其中的任意一个字符串
* 代表0,1或者多个其前的字符
+ 代表1个或者多个其前的字符
string{N}字符串出现的N次
字符串{M,N}字符串最少出现M次,最多出现N次

select * from cms_admin where username REGEXp '^t';

原文地址:https://www.cnblogs.com/3ddan/p/10361690.html