MySQL数据库 您所在的位置:网站首页 sql命令分为几类类型 MySQL数据库

MySQL数据库

2024-07-07 18:37| 来源: 网络整理| 查看: 265

本文主要讲述了MySQL数据库的多种查询方式,且MySQL语句是需要记忆的,但是有随时忘记的可能,如果读者喜欢我的文章的话可以选择收藏该文章,在你忘记的时候可以随时查看!

1、基本查询 查询所有字段: select * from 表名; 查询指定字段: 方式一:select 列1, 列2,…… from 表名;方式二:select 表名.列1, 表名.列2,…… from 表名; 使用 as 给字段起别名: select 字段 as 别名…… from 表名;哪列在前先出现哪列。 可以通过 as 给表起别名: select 别名.列1, 别名.列2,…… from 表名 as 别名;注意:起了别名就要用别名,不能在用表名,否者出现错误!如下: select 表名.列1, 表名.列2,…… from 表名 as 别名; 查询过程中的去重(消除重复行): 添加 distinct 字段 实现去重。查询字段中的所有存在的结果:select distinct 字段名 from 表名; 2、条件查询 select …… from 表名 where 条件;比较运算符: 大于>小于=小于等于18 and ageselect * from 表名 where age=18 or age=12 or age=34; not in (数据1, 数据2, ……) 不在非连续的范围之内: select * from 表名 where age not in (18, 12, 34); between … and … 表示在一个连续的范围内: select * from 表名 where age between 18 and 34; 等价于===>select * from 表名 where age>=18 and age 30; select gender, group_concat(name) from 表名 group by gender having avg(age) > 30; 6、分页查询 limit count 限制本次查询出来最多的数据个数: select * from students limit 3; limit start, count: start 代表从第几个数据开始 其中0 代表第一个数据 count 代表限制本次查询出来最多的数据个数查询id 3到5 的数据: select * from students limit 2, 3; 查询页数的使用: 每页显示x个,第1页: select * from 表名 limit 0, x; 每页显示x个,第2页: select * from 表名 limit (2-1)*x, x; 每页显示x个,第3页: select * from 表名 limit (3-1)*x, x; 每页显示x个,第4页: select * from 表名 limit (4-1)*x, x; 总结:每页显示x个,第n页: select * from 表名 limit (n-1)*x, x; 每页显示2个,显示第6页信息,按照年龄从小到大排列: 错误:select * from 表名 limit 10, 2 order by age asc 原因:limit 在最后! 7、链接查询 当查询结果的列表来源于多张表时,需要将多张表连接成一个大的数据库,在选择合适的列返回。mysql 支持三种类型的链接查询: inner 内连接查询: 查询的结果为两个表中匹配到的数据。 left 左链接查询: 查询的结果为两个表匹配到的数据,左表特有的数据,对于右表中不存在的数据用null补充。 right 右链接查询: 查询的结果为两个表匹配到的数据,右表特有的数据,对于左表中不存在的数据用null补充。 左、右链接查询只需会一种即可,因为可以通过调换两表的位置来实现右链接! 内连接查询: 表A inner join 表B on 条件;查询 students表中 有能够对应classes表中班级 的学生信息及班级信息: select * from students inner join classes on students.cls_id=classes.id; 左链接查询: 表A left join 表B on 条件;左表特有的数据,对于右表中不存在的数据用null补充。查询 每位学生对应的班级信息,不存在班级的用null表示: select * from students left join classes on students.cls_id=classes.id; 查询 没有对应班级的学生:得到新表的结果,用havingwhere也可行,但不推荐使用! select * from students left join classes on students.cls_id=classes.id having classes.id is null; 右链接查询: 表A right join 表B on 条件;右表特有的数据,对于左表中不存在的数据用null补充。 8、自关联 一个表按成两个表链接: select * from 表名 as 别名1 inner join 表名 as 别名2 on 条件; 9、子查询 一个select中嵌套一个select!标量子查询: 查询最高的男生信息: select * from students where height=(select max(height) from students); 列级子查询: 查询学生的班级号能够对应学生信息: select * from students where cls_id in (select * from classes); 10、合并查询结果 union all 关键字可以将多条select语句组合成一个结果集。select id, name from students where id


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有