数据库查询、插入、更新、删除数据

查询数据是指从数据库中获取所需要的数据。查询数据是数据库操作中最常用,也是最重要的操作。用户可以根据自己对数据的需求,使用不同的查询方式。通过不同的查询方式,可以获得不同的数据。在 MySQL中是使用SELECT语句来查询数据的。

基本查询语句

SELECT 属性列表 FROM表名和视图列表  [WHERE条件表达式1]  [GROUPBY 属性名1 [HAVING条件表达式2]]   [ORDERBY 属性名2[ASC|DESC]]

select id,name,age,sex from table1 where age<26 order by id desc;

单表查询

查询所有字段

//列出表的所有字段
select id,name,age,sex from table1;

//用*查询所有字段
select *from employee;

//查询指定字段
select id  from table1;

//查询指定记录
select id,name,age,sex from table1 where id=001;

//带in关键字的查询
select *from employee where id in(001,005);

//between and 范围查询
select *from employee where age between 15 and 25;

//like字符匹配查询
select *from employee where name like 'R';
select *from employee where name like 'R%';

//查询空值
select *from employee where name is null;

//and多条件查询
select *from employee where id=1 and age=17;

//or多条件查询
select *from employee where id=1 or age=17;

//查询结构排序
select *from employee order by age desc;

分组查询

//用group by来分组   只显示每个分组的一条记录
select * from information group by sex;

//limit  
select * from information limit 2;
select * from information limit 1,2;  //第一个之后显示两条

使用集合函数查询

连接查询

内连接查询

 select a.*, b.* from a, b wherea.xid=b.xid

外连接查询

SELECT 属性名列表 FROM 表名1 LEFT|RIGHT JOIN 表名2  ON 表名1.属性1=表名2.属性2;

LEFT JOIN            左表全记录,右表符合条件

RIGHT JOIN         右表全记录,左表符合条件

子查询

IN

EXISTS 表示存在,内层查询语句不返回查询的记录,而是返回一个真假值(true|false)

ANY任意一个值

         SELECT * FROM computer_stu WHERE scrore>=ANY(SELECT score FROM scholarship)

ALL 满足所有条件

为表和字段取别名

表名 表的别名

属性名 [AS] 属性的别名

使用正则表达式查询

属性名 REGEXP ‘匹配方式’

^                         字符串开始

$                         字符串结束

.                           任意一个字符,包括回车和换行

[字符集合]            匹配字符集合中的任一字符

S1|S2|S3              三者之任一

*                          任意多个

+                         1+个

字符串{N}             字符串出现N次

字符串{M,N}         字符串出现至少M次,至多N次

SELECT * FROMinfo WHERE name REGEXP ‘ab{1,3}’;

插入数据

为表的所有字段插入数据

1、INSERT语句中不指定具体的字段名      

insert into 表名 values (值1,值2…值n)

2、INSERT语句中列出所有字段

insert into 表名 (属性1,属性2…属性n) values (值1,值2…值n)

为表的指定字段插入数据

insert into 表名 (属性1,属性2,属性3) values (值1,值2,值3) 

同时插入多条数据      

insert into 表名 (属性1,属性2…属性n) values (值1,值2…值n),

                (属性1,属性2…属性n) values (值1,值2…值n),

                ...

                (属性1,属性2…属性n) values (值1,值2…值n);

MySQL特有的

将查询结果插入到表中

insert into 表名 (属性1,属性2…属性n)

      select 属性列表 from 表名2where 条件表达式

use mysql;

create table user1(user char(16) not null);

insert into user1(user) select user from user;

                  

更新数据    

update 表名

         set 属性1=值1,属性2=值2,…

         where 条件表达式;

删除数据    

delete from 表名 [条件表达式];

猜你喜欢

转载自blog.csdn.net/qq_41078889/article/details/113035202