1、mysql 中执行 sql字符串
set @strSql='select 1200 as item'; prepare select_sql from @strSql; execute select_sql; #输出 +------+ | item | +------+ | 1200 | +------+
2、字符类型字段转换成整型
select cast( '123' as signed) as id; +-----+ | id | +-----+ | 123 | +-----+
3、将查询结果批量写入表中
INSERT INTO tb_1(id,title) select id,title from tb_2;
4、判断存储过程是否存在,存在则删除
drop procedure if exists b2b_bidding.temp_proc_update_zb_table_uid;
5、简单存储过程定义
CREATE PROCEDURE proc_modify_tb1_id() BEGIN #定义变量 DECLARE _max_uid INTEGER; DECLARE _table_name VARCHAR(1000); # 招标附属表 b2b_bidding.bid_announcements_expand set _max_uid=( select MAX(CAST(str_id AS signed))+1 FROM tb_1) ; set _table_name='tb_1'; IF EXISTS(select * FROM tb_id_generation where table_name=_table_name) THEN UPDATE tb_id_generation set table_id= _max_uid where table_name=_table_name; ELSE INSERT into tb_id_generation (table_name,table_id ) VALUES (_table_name,_max_uid); END IF ; END; #执行存储过程 CALL proc_modify_tb1_id();
6、常用INSERT/UPDATA语句
6.1》 通过 IGNORE 实现插入数据主键冲突,SQL执行不成功但不抛出异常。
INSERT IGNORE INTO mytab(ID,Title,`WHERE`) VALUES (1,'aaaa','aaaaaa');
6.2》主键冲突,则通过 on DUPLICATE KEY 执行UPDATE
INSERT IGNORE INTO mytab(id,title,`short_title`) VALUES (1,'XX有限公司','XX公司') on DUPLICATE KEY UPDATE title='update-XX有限公司',`short_title` ='update——XX公司';
6.3 》存在满足条件记录,则添加记录进入表中
INSERT INTO mytab(ID,Title,`WHERE`) SELECT 3,'3','333' from mytab where EXISTS (select 1 from mytab where 1<>1);
6.4》存在主键相同的记录着直接替换已经存在的记录 字段值
REPLACE INTO mytab SELECT 1, 't1','tttttt2' FROM mytab;
7、find_in_set函数,匹配字段属性值
mysql> SELECT * from test.my_tb WHERE find_in_set(parent_code,'01,02'); +----+-------------+------+ | id | parent_code | code | +----+-------------+------+ | 1 | 01 | 001 | | 2 | 01 | 001 | | 3 | 02 | 001 | | 4 | 01 | 003 | | 5 | 02 | 002 | +----+-------------+------+
8、根据 汉字对应的首字母排序
ORDER BY CONVERT(chinese_file USING gbk )