sql
sql update去除某一列的空白字符
用REPLACE函数,把空格替换成 ”(空字符串)。
例:去除 表table 中 col 列的空字符
去除空格符:update table set col = REPLACE(col,’ ‘,”)
还有tab制表符(即char(9)),显示效果类似空格。
去除制表符:update table set col = REPLACE(col,CHAR(9),”)
添加修改字段
添加字段示例:alter table tablename add columnName varchar(64) DEFAULT ” COMMENT ‘注释’ after(before) columnNameX;
修改字段:ALTER TABLE user10 MODIFY card CHAR(10) AFTER test;
时间字段
mysql建表时,都要加这个字段
updated_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
唯一索引
创建: CREATE UNIQUE INDEX uk_k1_k2 ON table_name(k1,k2);
删除: ALTER TABLE table_name DROP INDEX uk_k1_k2;
使用经验
- 数据量很小查询频繁的表最好做一个本地缓存。
update与join连用
在update语句中使用select出的结果给字段set值
UPDATE tab_a as a INNER JOIN tab_b as b ON a.id=b.a_id
SET a.amount=b.amount where a.amount is NULL
sql语句中使用条件语句
select amount,
CASE source
WHEN ‘1’ THEN ‘11’
WHEN ‘2’ THEN ‘22’
WHEN ‘3’ THEN ‘33’
ELSE ”
END AS source,
from table_a
where id=1;
Mysql
mysql连接等待超时引发的异常
当mysql链接空闲超过默认时长(没做配置的话),链接会自动断开,这时再去访问会发生如下异常:
### Error querying database. Cause: com.mysql.cj.jdbc.exceptions.CommunicationsException:
The last packet successfully received from the server was 216,960,986 milliseconds ago.
The last packet sent successfully to the server was 216,960,987 milliseconds ago.
is longer than the server configured value of 'wait_timeout'.
You should consider either expiring and/or testing connection validity before use in your application,
increasing the server configured values for client timeouts,
or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
### The error may exist in URL [jar:file:****]
### The error may involve ****-Inline
### The error occurred while setting parameters
### SQL: ****
为了避免此问题可以给mysql加一个配置:
idleConnectionTestPeriod: 3600
mysql会每隔3600自动去发起一条sql以保持数据库链接,另外这个时间一定要小于数据库链接的等待超时时间才行。
数据库迁移注意事项
在给表作数据迁移时,最好先不要作索引,会影响迁移速度。