您的位置:首页 > 数据库

SQL语句——入门级

2015-08-29 17:35 246 查看
入门级别的sql语句,“--”两条横线表示sql语句的注释

表:

id     name   age   height
2015102 老王   68    170.3
20150101 张三   null   null
20150102 小王   8     170.3
20150102 老王   68     170.3
20150102 老王   68     170.3
20150102 老王   68     170.3
20150102 老王   68     170.3
20150102 老王   68    170.3

-- 数据库(database):存储数据的仓库,
-- 数据库(database)--数据表(table)--列名(字段-field)--数据(值-value)
--创建表
--(在sqlite数据库中创建表的时候定义数据类型的起不来限制数据类型的作用的
--因为sqlite的数据的数据类型数弱类型,它会根据用户输入的数据进行自动的识别并添加
--到数据库表中,和大多数数据库一样,sqlite 是大小写不敏感的)

-- sqlite 数据库中的五类数据类型:1、整数-integer  2、浮点数(小数)-real
-- 3、文本-text  4、二进制文件(图片、声音为典型代表)-blob  5、空类型-null
--
--
--CREATE TABLE 表名称
--(
--列名称1 数据类型,
--列名称2 数据类型,
--列名称3 数据类型,
--....
--)
-- 字段与字段直接用“,”号隔开,字段的一些属性用空格“ ”隔开,最后一个字段不要有“,”
create table person(
id integer not null,
name text,
age integer,
height real
)

-- 删除表
drop table person

--对数据库的操作无非就是CRUD
-- C:增加(增)-Create
-- R:读取(查)-Retrieve
-- U:更新(改)-Update
-- D:删除(删)-Delete

--查:获取表中全部数据
select * from person

--增:添加数据--文本类型要用双引号("")或者单引号('')括起来
--insert into 表 values (值1, 值2, 值3...)
-- 或者指定添加内容
-- insert into 表(字段1, 字段2, ...) values (值1, 值2, 值3...)
-- 注意:如果字段类型定义为数值型,如果插入了文本型,虽然不会报错,但是无法插入,显示的值可能为0
insert into person values(20150102, '老王', 68,170.3)
insert into person(id, name) values (20150101, '张三')

--删:删除数据(不能删除某个数据)
--格式:delete from 表 where 。。。
--像MySQL还可以:delete * from 表 where 。。。(比sqlite多了个“*”)
-- 进行删除操作要谨慎,记得加上条件+加上条件+加上条件。否则会将整张表的数据删除
delete from person where id=20150102

-- 改:修改数据
-- update 表 set 列名称 = 新值 , 列名称=新值 。。。  where 列名称 = 某值
-- 记得修改的条件,如果你想修改这个表中改字段(列名称)的所有值为相同的话可以不加条件
update person set name='小王', age=8 where id=20150102

-- 查:查询数据(重点+难点)
-- 格式 select * from 表
-- 查询所有数据 :
select * from person

-- 使结果中不出现重复数据(例如id)
select distinct id from person

-- 模糊查询:%:所有字符;_单个字符
select * from person where name like'老_'

-- 排序:降序:order by 字段 desc 升序:order by 字段 desc
select * from person order by age desc

-- 统计 :总数count(*);最大值max(字段);最小值min(字段);avg(字段)
select max(age) from person

-- 选择前几项:limit 开始, 数量;不要加括号,开始下标从0开始,一般都是放在语句的最后面,也有用 top 数值 的
-- eg:获取前三条
select * from person limit 0,3

-- 分组 : group by 字段
-- eg: 统计不同id 的人数;相同字段的分为一组
select count(*) from person group by id

-- 比较 >, <, =, !=
select * from person where id=2015102

-- 在 。。 之间 :between 值1 and  值2,介于两个值之间的数据范围。这些值可以是数值、文本或者日期
select * from person where id between 201501 and 20151110

-- 包含 : 字段 in(值1,值2。。)
select * from person where id in(1001,1002,1003,20150101)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: