发布网友
共1个回答
热心网友
SQL是一种特殊用途的编程语言,主要用于数据库查询和程序设计。它用于存储、检索和管理关系型数据库系统中的数据。接下来,我将分享一些SQL语句编写的基础技巧,主要包括增删改查操作。请看下面的详细说明:
1、增(插入数据)
1.1 插入单行数据
使用 `insert` 语句,可以将数据插入指定表中。格式如下:
sql
insert [into] 表名 (列名) values (列值)
例如,将数据插入到 `Students` 表中:
sql
insert into Students (姓名,性别,出生日期) values ('开心朋朋','男','1980/6/15')
1.2 将现有表数据添加到新表中
使用 `insert` 与 `select` 结合,可以将数据从一个表复制到另一个表:
sql
insert into 新表 (列名) select 原表列名 from 原表名
例如,将 `Strdents` 表的数据插入到 `tongxunlu` 表中:
sql
insert into tongxunlu ('姓名','地址','电子邮件')
select name,address,email from Strdents
1.3 直接从现有表创建新表并填充数据
使用 `select` 语句,可以创建新表并从源表填充数据:
sql
select 新建表列名 into 新建表名 from 源表名
例如,创建并填充 `tongxunlu` 表:
sql
select name,address,email into tongxunlu from strdents
1.4 使用 `union` 关键字合并数据插入多行
结合 `union`,可以将多条数据插入同一表:
sql
insert 表名 (列名) select 列值 union select 列值
例如,向 `Students` 表插入多行数据:
sql
insert Students (姓名,性别,出生日期)
select '开心朋朋','男','1980/6/15' union
select '蓝色小明','男','19****'
2、删(删除数据)
2.1 删除满足条件的行
使用 `delete` 语句,根据条件删除表中的特定行:
sql
delete from 表名 [where 删除条件]
例如,删除 `a` 表中 `name` 为 '开心朋朋' 的行:
sql
delete from a where name='开心朋朋'
2.2 删除整个表
使用 `truncate` 语句,可以删除表中所有数据,但保留表结构:
sql
truncate table 表名
例如,删除 `tongxunlu` 表中的所有数据:
sql
truncate table tongxunlu
3、改(更新数据)
使用 `update` 语句,可以更新表中的数据:
sql
update 表名 set 列名=更新值 [where 更新条件]
例如,更新 `tongxunlu` 表中 `姓名` 为 '蓝色小明' 的 `年龄` 为 18:
sql
update tongxunlu set 年龄=18 where 姓名='蓝色小名'
4、查(查询数据)
4.1 精确查询
使用 `select` 语句,可以精确查询表中的数据。
4.1.1 查询所有数据行和列
sql
select * from 表名
例如,查询 `a` 表中所有行和列:
sql
select * from a
4.1.2 查询部分行列(条件查询)
sql
select 列名 from 表名 where 查询条件表达式
例如,查询 `a` 表中 `f` 等于 5 的所有行,并显示 `i`, `j`, `k` 列:
sql
select i,j,k from a where f=5
4.1.3 使用 AS 更改列名
sql
select 列名 as 列名 AS 更改后的列名 from 表名 where 查询条件表达式
例如,查询 `a` 表中性别为男的所有行,显示 `name` 列,并将其改名为(姓名):
sql
select name as 姓名 from a where xingbie='男'
4.1.4 查询空行
sql
select 列名 from 表名 where 列名 is null
例如,查询 `a` 表中 `email` 为空的所有行,并显示 `name` 列:
sql
select name from a where email is null
4.1.5 使用常量
sql
select 列名, 常量 as 列名 from 表名
例如,查询 `a` 表,显示 `name` 列,并添加 `地址` 列,其列值都为 '唐山':
sql
select name, '唐山' as 地址 from Student
4.1.6 查询返回行数(使用 top 关键字)
sql
select top 行数 列名 from 表名
例如,查询 `a` 表中前 6 行的 `name` 列:
sql
select top 6 name from a
4.1.7 查询排序(使用 order by 关键字)
sql
select 列名 from 表名 where 查询条件表达式 order by 排序的列名 [asc or desc]
例如,查询 `a` 表中 `chengji` 大于等于 60 的所有行,并按降序显示 `name` 列:
sql
select name from a where chengji>=60 order by desc
4.2 模糊查询
4.2.1 使用 `like` 关键字进行模糊查询
sql
select * from 表名 where 列名 like 查询模式
例如,查询 `a` 表中 `name` 字段第一个字为 '赵' 的记录:
sql
select * from a where name like '赵%'
4.2.2 使用 `between` 关键字在某个范围内进行查询
sql
select * from 表名 where 列名 between 起始值 and 结束值
例如,查询 `a` 表中 `nianling` 在 18 到 20 之间的记录:
sql
select * from a where nianling between 18 and 20
4.2.3 使用 `in` 关键字在列举值内进行查询
sql
select 列名 from 表名 where 列名 in (列举的值)
例如,查询 `a` 表中 `address` 值为 '北京'、'上海' 或 '唐山' 的记录:
sql
select name from a where address in ('北京','上海','唐山')
SQL功能包括但不限于: