MySQL条件查询

--基本查询
select
* from 表名 where 判断条件;

模糊查询

select * from 表名 where name like "张%";   查询姓张的所有数据

select * from 表名 where name like "张_";    查询两个字姓张的    


select * from 表名 where name relike "^张"; relike是用正则表达式查询 以张开头的

范围查询

select * from 表名 where name in ("张三","李四");    查询姓名为张三和李四的


select * from 表名 where age between 13 and 14;    查询年龄在13~20岁之间的
select * from 表名 where age not between 13 and 14;  查询年龄不在13~20岁之间的

select * from 表名 where age is not null; 判断年龄不能为空

排序

select * from 表名 where age between 12 and 20 order by;    不带参数为升序

select * from 表名 where age between 12 and 20 order by dasc; 从大到小

聚合函数

count()
select
count(*) asfrom 表名 where 性别="男"; 统计男性有多少人

max,min
select max(身高) as 最高from 表名 where 性别="男";   统计男最高的身高

select sum(age) as 年龄 from 表名; 统计平均年龄

round()
select round(avg(身高),1) as 平均身高 from 表名;   保留1为小数,多的四舍五入


分组
group by
select count(*) from 表名 group by 性别; 分别统计男女有多少人

select 性别,group_concat(name) from 表名 group by 性别; 查询每个性别中有哪些人的名字


设置显示数据条数
limit
select name,数学 from 表名 order by desc 数学 limit 3;
显示数学最高分的前三名

select * from 表名 limit 0,5; 显示第一条到第五条
select * from 表名 limit 1,5;     显示第二条到第六条
 

链接

liner  内连接
left   ·左连接
right   右连接
select
* from 表1 liner 或 leftright join 表2 on 表1.列 = 表2.列;

select * from 表1 liner 或 left 或 right join 表2 on 表1.列 = 表2.列 having 新表判断条件;     在新链接出来的表用  having    在原表用 where

创建关联设置外键

alter table 表名1 add foreign key (主键字段) references 表名2(副键字段)
原文地址:https://www.cnblogs.com/wocaonidaye/p/12390660.html