频道栏目
首页 > 资讯 > SQL Server > 正文

常用的SQL语句

17-09-19        来源:[db:作者]  
收藏   我要投稿

常用的SQL语句

常用的SQL语句整理。

数据库操作

create database dbname; //创建数据库

drop database dbname; //删除数据库

表操作

create table tablename(column_name1 data_type(size) [not null] [primary key],column_name2 data_type(size) [not null],..)

/* 创建表

*column_name 参数规定表中列的名称。

*data_type 参数规定列的数据类型(例如 varchar、integer、decimal、date 等等)。 *size 参数规定表中列的最大长度。

*not null:可选,默认接受null值

*primary key:可选,设置主键,唯一,不为null值。

*/

drop table table_name //删除表

truncate table table_name //只删除表内的数据

列操作

alter table table_name add column_name datatype //添加列

alter table table_name drop column column_name //删除列

基本操作

选择:select * from table_name where 过滤条件

插入:insert into table_name (field1,field2) values(value1,value2)

删除:delete form talbe_name where 过滤条件

更新:update table_name set field1=value1,field2=value2,.. where 过滤条件

排序:select * from table_name order by field [desc]

总数:select count as totalcount form table_name

求和:select sum(field) as totalvalue form table_name

平均:select avg(field) as avgvalue form table_name

最大:select max(field) as maxvalue form table_name

最小:select min(field) as minvalue form table_name

高级语句

1.模糊查询

select * from table_name where field like pattern; //选择field等于pattern的数据。

select * form table_name where field like 'G%' //选择field以字母"G"开头的数据

select * form table_name where field like '%G' //选择field以字母"G"结尾的数据

select * from table_name where field like '%G%' //选择field包含字母"G"的数据

select * from table_name where field not like '%G%' //选择field不包含字母"G"的数据

2.多个值查询

select * from table_name where field in (value1,value2,...) //选择field为"value1"或"value2"的数据

select * from table_name where field not in (value1,value2,...) //选择field不是"value1"或"value2"的数据

3.区间查询

select * from table_name where field between value1 and value2 //选择field介于value1与value2两个值之间的数据。(可以是数值、文本或者日期)

select * from table_name where field not between value1 and value2 //选择field不在value1与value2两个值之间的数据。

3.多表查询

select * from table1 join table2 on table1.id=table2.sid;

不同的 SQL JOIN 类型:

INNER JOIN :如果表中有至少一个匹配,则返回行。(join与inner join是相同的)

LEFT JOIN:即使右表中没有匹配,也从左表返回所有的行

RIGHT JOIN:即使左表中没有匹配,也从右表返回所有的行

FULL JOIN:只要其中一个表中存在匹配,则返回行

4.合并

select field from table1 union select field from table2; //合并两个或多个 SELECT 语句的结果,默认地,UNION 操作符选取不同的值。

select field from table1 union all select field from table2; //合并两个或多个 SELECT 语句的所有结果.

5.分组

select id,sum(table.count) as nums from table group by field; //一般会结合sum或count来使用

总结

SQL复杂的查询都是基于基础的语句,熟悉掌握了基础,你就能更加快速的查询你想要的数据。

相关TAG标签
上一篇:Hbase之Shell基本命令
下一篇:oracle之trunc函数
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站