标签:smi row das exec roc handle iter from where
l临时表: select * from tb where id <10;
指定映射: select id ,name 1, sum(x) /count()
条件: case when id >8 then 1 else 0 end
三元运算: if(is null(xx),0,1) c = a if a < b else b turn 返回 a false 返回 b
左右连表:join 上下连表 union
视图:
-创建 CREATE VIEW v1 AS
SELECT * FROM u_q
create view name as sql
-修改 alter view name as sql
-删除 drop view name
触发器
-当对某张表做:增删改操作时,可以使用触发器自定义关联行为
DELIMITER // #修改终止符
CREATE TRIGGER t1 BEFORE INSERT ON USER FOR EACH ROW
BEGIN
INSERT INTO u_q(q) VALUE (5);
END //
DELIMITER ; # 还原终止符
即创建t1表时会顺带插入数据
函数
SELECT CURDATE()#时间
SELECT CHAR_LENGTH(‘wdasda‘)#长度
SELECT CONCAT(‘alex‘,‘smith‘)#合并
时间格式化
SELECT DATE_FORMAT(ctime, "%Y-%m")
自定义函数
DELIMITER \\
CREATE FUNCTION f1 (
i1 INT,
i2 INT)
RETURNS INT
BEGIN
DECLARE num INT DEFAULT 0;
SET num = i1 + i2;
RETURN (num);
END \\
DELIMITER ;
DELIMITER \\
CREATE FUNCTION f1(
i1 INT,
i2 INT)
RETURNS INT
BEGIN
DECLARE num INT DEFAULT 0;
SET num = i1 + i2;
RETURN(num);
END \\
DELIMITER ;
存储过程:
保存在MySQL上的一个别名 => 一坨SQL语句 precedure() 用于替代程序员写SQL语句
用参数之前要声明declare - - 麻烦
方式一:
MySQL: 存储过程
程序:调用存储过程
方式二:
MySQL:。。
程序:SQL语句
方式三:
MySQL:。。
程序:类和对象(SQL语句)
1 简单
delimiter //
create procedure p1()
begin
select * from user ;
insert into teacher(tname) value (‘kk‘);
end //
delimiter ;
call p1();
2 传参数(in,out ,inout)
delimiter //
create procedure p2(
in n1 int ,
in n2 int
)
begin
select * from student where sid >n1;
end //
delimiter ;
call p2(12,2)
cursor.callproc(‘p2‘,(12,2))
3 参数 out(用于一个可以返回的结果)
DELIMITER //
CREATE PROCEDURE p4 (
IN n1 INT,
OUT n2 VARCHAR(20)
)
BEGIN
SET n2 = ‘执行成功‘;
SELECT * FROM USER WHERE nid > n2;
INSERT INTO quanxian(POWER) VALUE (‘choudidi‘);
END //
DELIMITER ;
set @v1 = 10;
call p2(12,@v1)
select @v1;
pymysql:
cursor.callproc(‘p4‘,(2,3))
result = cursor.fetchall()
print(result)
4 游标:用与循环
DELIMITER //
CREATE PROCEDURE p6()
BEGIN
#声明循环参数
DECLARE row_id INT;
DECLARE row_num INT;
DECLARE done INT DEFAULT FALSE;
DECLARE temp INT;
#声明游标 游标done
DECLARE my_cursor CURSOR FOR SELECT id ,num FROM A;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN my_cursor;
xx:LOOP (循环)
FETCH my_cursor INTO row_id , row_num;
IF done THEN
LEAVE xx;
END IF;
SET temp = row_id + row_num;
INSERT INTO B(number) VALUE (temp);
END LOOP xx;
CLOSE my_cursor;
END //
DELIMITER ;
5 动态执行SQL (防止sql注入)
DELIMITER //
CREATE PROCEDURE p7(
IN tpl VARCHAR(244),
IN ARG INT
)
BEGIN
#预编译
#sql = 格式化 tpl+arg
#执行
SET @xo = ARG;
PREPARE xxx FROM ‘select * from student where sid > ?‘;
EXECUTE xxx USING @xo;
DEALLOCATE PREPARE prod;
END //
DELIMITER ;
CALL p7(‘select * from tb where id> ?‘,9)
标签:smi row das exec roc handle iter from where
原文地址:https://www.cnblogs.com/kangkang1999/p/13233260.html