sql常见用法

来源:互联网 发布:手机防广告软件 编辑:程序博客网 时间:2024/06/11 14:24

1.获取sql语句的执行计划

EXPLAIN SELECT * FROM EMPLOYEES

explain关键字一般放在SELECT查询语句的前面,用于描述MySQL如何执行查询操作、以及MySQL成功返回结果集需要执行的行数。explain 可以帮助我们分析 select 语句,让我们知道查询效率低下的原因,从而改进我们查询,让查询优化器能够更好的工作。 

2.数据库连接字符串

SQLite数据库只支持用连接符号”||”来连接字符串

SELECT last_name||" "||first_name AS Name FROM employees

MySQL、SQL Server、Oracle等数据库支持CONCAT方法

SELECT concat_ws(' ',last_name,first_name) AS Name FROM employees

3.sqllite 时间默认为当前时间

DEFAULT是为该字段设置默认值,且默认值为(datetime(‘now’,’localtime’)),即获得系统时间

 create table actor(    'actor_id' smallint(5) not null primary key,    'first_name' varchar(45) not null,    'last_name' varchar(45) not null,    'last_update' timestamp not null default (datetime('now','localtime')));

4.批量插入sql

insert into actor(actor_id,first_name,last_name,last_update) values('1','PENELOPE','GUINESS','2006-02-15 12:34:33'),('2','NICK','WAHLBERG','2006-02-15 12:34:33')

5. 插入重复记录

如果存在忽略(insert or ignore)

insert or ignore into actor values('3','ED','CHASE','2006-02-15 12:34:33')

如果存在更新记录(insert or replace)

insert or replace into actor values('3','ED','CHASE','2006-02-15 12:34:33')

6.查询的数据插入到table

insert into actor_name select first_name,last_name from actor

7.创建索引

创建唯一索引

create unique index uniq_idx_firstname on actor(first_name);

创建普通索引

create index idx_lastname on actor(last_name);

8. 创建视图

create view actor_name_view asselect first_name as fist_name_v, last_name as last_name_v from actor

9. 强制索引

SQLite中强制索引查询使用

select * from salaries INDEXED by idx_emp_no where emp_no = '10005'

MYSQL中强制索引查询使用

select * from salaries force index(idx_emp_no) where emp_no = '10005';

10.在sqlsever2000中用datatime字段

字段的格式为yyyy-MM-dd HH:mm:ss如:alter table actor add column create_date datetime NOT NULL default '0000-00-00 00:00:00'; 

11.sqlite创建触发器

create trigger audit_log after insert on employees_testbegin   insert into audit values(NEW.ID,NEW.NAME);end ; 

12.更新若干记录时用,隔开

update titles_test set from_date='2001-01-01' , to_date=NULL where to_date='9999-01-01'

13.replace更改记录

replace into titles_test values(5,'10005','Senior Engineer','1986-06-26', '9999-01-01')

14.修改表名

rename table titles_test to titles_2017② alter table titles_test rename to titles_2017
原创粉丝点击