mysql 点滴

1,concat
举个例子 select concat('aa','bb');------------最终显示的就是 aabb,同时,concat有 to_char的作用,就是把其他类型转成varchar类型的

2,存储过程中 if else

         create procedure text(
                      out rtn int
                                  )
             begin
           declare LoginId INT default 0;
           set rtn=1;
          IF LoginId = 3
          THEN
          set rtn=2;
          ELSEIF LoginId = 0
          THEN
          set rtn=3;
          ELSE
          set rtn=4;
           END IF;
             end

   3,LOCATE

类似indexOf方法

LOCATE(substr,str)
 

返回子串substr在字符串str第一个出现的位置,如果substr不是在str里面,返回0.
mysql> select LOCATE('bar', 'foobarbar');
-> 4
mysql> select LOCATE('xbar', 'foobar');
-> 0 

   4,FIND_IN_SET(str,strlist)

假如字符串str 在由N 子链组成的字符串列表strlist 中,则返回值的范围在 1 到 N 之间。
一个字符串列表就是一个由一些被‘,’符号分开的子链组成的字符串。如果第一个参数是一个常数字符串,而第二个是type SET列,则   FIND_IN_SET() 函数被优化,使用比特计算。
如果str不在strlist 或strlist 为空字符串,则返回值为 0 。如任意一个参数为NULL,则返回值为 NULL。这个函数在第一个参数包含一个逗号(‘,’)时将无法正常运行。 

 

  5,group_concat

函数语法:

group_concat( [DISTINCT]  要连接的字段   [Order BY 排序字段 ASC/DESC]   [Separator '分隔符'] ) 

select id, group_concat(price) from goods group by id;  

select id,group_concat(price separator ';') from goods group by id;  

select id,group_concat(distinct price) from goods group by id;  

select id,group_concat(price order by price desc) from goods group by id;  

  6,UNIX_TIMESTAMP,FROM_UNIXTIME

SELECT UNIX_TIMESTAMP('2014-12-25');

输出:1419436800

SELECT FROM_UNIXTIME(1419436800);

输出:'2014-12-25'

  7,date_sub,date_add 

select date_add('2008-08-08 12:00:00', interval -8 hour); -- 2008-08-08 04:00:00
select date_sub('2008-08-08 12:00:00', interval 8 hour); -- 2008-08-08 04:00:00
SELECT UNIX_TIMESTAMP(CONCAT( DATE_SUB(curdate(), INTERVAL 1 DAY) ,' 10:00'));-- 获得昨天10:00时间戳

  8,用临时表批量更新

创建临时表,先更新临时表,然后从临时表中update

create temporary table tmp(id int(4) primary key,dr varchar(50));
insert into tmp values  (0,'gone'), (1,'xx'),...(m,'yy');
update test_tbl, tmp set test_tbl.dr=tmp.dr where test_tbl.id=tmp.id;

注意:这种方法需要用户有temporary 表的create 权限

   9,游标

DELIMITER $$

DROP PROCEDURE IF EXITS cursor_example$$
CREATE PROCEDURE cursor_example()
READS SQL DATA
BEGIN
DECLARE l_employee_id INT;
DECLARE l_salary NUMERIC(8,2);
DECLARE l_department_id INT;
DECLARE done INT DEFAULT 0;
DECLARE cur1 CURSOR FOR SELECT employee_id, salary, department_id FROM employees;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;

OPEN cur1;
emp_loop: LOOP
FETCH cur1 INTO l_employee_id, l_salary, l_department_id;
IF done=1 THEN
LEAVE emp_loop;
END IF;
END LOOP emp_loop;
CLOSE cur1;
END$$
DELIMITER ;



 

posted @ 2014-10-17 11:47  xjt360  阅读(185)  评论(0编辑  收藏  举报