MySQL常用语法

2018-01-05  本文已影响0人  octcms
存储过程PROCEDURE
DROP PROCEDURE IF EXISTS usp_test;
DELIMITER //
CREATE PROCEDURE `usp_test`()
COMMENT ‘存储过程注释’
BEGIN
  -- 需要执行的SQL
  SELECT * FROM tb_a;
  SELECT * FROM tb_b;
END//
DELIMITER ;
函数FUNCTION
DROP FUNCTION IF EXISTS `fn_test`;
DELIMITER //
CREATE FUNCTION `fn_test`(`in_name` VARCHAR(50)) RETURNS varchar(50) CHARSET utf8
BEGIN
     -- 函数体
     set @a=’Name=’;
     return concat(@a,in_name);
END//
DELIMITER ;
事件EVENT
DROP EVENT IF EXISTS `evt_test`;
DELIMITER //
CREATE EVENT `evt_task_member_statistics` ON SCHEDULE EVERY 1 DAY STARTS ‘2016-07-07 00:00:00’
ON COMPLETION PRESERVE ENABLE COMMENT ‘注释’ DO BEGIN
  -- 需要执行的SQL
  SELECT * FROM tb_a;
END//
DELIMITER ;     

备注:MYSQL默认是关闭事件机制的,需要自行开启
SET GLOBAL event_scheduler = 1; — 开启event
show variables like ‘event_%’; — 查看event开启状态

SQL语句性能分析
explain
select * from wp_posts a where a .ID= 5 and a .post_type= ‘post’;
创建临时表
DROP TEMPORARY TABLE IF EXISTS tmp_tb;
CREATE TEMPORARY TABLE tmp_tb (id int AUTO_INCREMENT PRIMARY KEY not null,service_id int not null);
无锁模式(Unlock)

MS SQL Server使用无锁查询模式只需要在表名后面加上(NOLOCK)

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
  -- SQL查询语句
  SELECT * FROM tb_a;
COMMIT ;

或者

SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
  -- SQL查询语句
  SELECT * FROM tb_a;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
触发器(TRIGGER)

插入前

CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW
BEGIN
    -- sql
END

插入后

CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW
BEGIN
    -- sql
END

删除前

CREATE TRIGGER tri_before_delete_tb1 BEFORE DELETE ON tb1 FOR EACH ROW
BEGIN
    -- sql
END

删除后

CREATE TRIGGER tri_after_delete_tb1 AFTER DELETE ON tb1 FOR EACH ROW
BEGIN
    -- sql
END

更新前

CREATE TRIGGER tri_before_update_tb1 BEFORE UPDATE ON tb1 FOR EACH ROW
BEGIN
    -- sql
END

更新后

CREATE TRIGGER tri_after_update_tb1 AFTER UPDATE ON tb1 FOR EACH ROW
BEGIN
    -- sql
END

本文会持续更新…

上一篇下一篇

猜你喜欢

热点阅读