MySQL简易入门

MySQL 是一个互联网绕不过去的坎,总觉得很简单,一切似乎都围绕着 CURD,但是不能脱离这个核心,本次的博客其 MySQL 的一些基本概念作为主题,力求用自己的语言,将其中的概念说清楚。今天是在银川的第二天,第一次坐完飞机,现在在见家长的过程中,偷得片刻悠闲,写点东西作为总结~一条SQL的执行流
阅读更多

MySQL备份记录

备份

命令行下具体用法如下:

mysqldump -u用戶名 -p密码 -d 数据库名 表名 > 脚本名;

导出整个数据库结构和数据
mysqldump -h localhost -uroot -p123456 database > dump.sql

导出单个数据表结构和数据
mysqldump -h localhost -uroot -p123456 database table > dump.sql

导出整个数据库结构(不包含数据)
mysqldump -h localhost -uroot -p123456 -d database > dump.sql

导出单个数据表结构(不包含数据)
mysqldump -h localhost -uroot -p123456 -d database table > dump.sql

数据还原

1、还原使用mysqldump命令备份的数据库的语法如下:
mysql -u root -p [dbname] < backup.sq

示例:
mysql -u root -p < C:\backup.sql

docker命令记录

安装及配置docker(基于Ubuntu)sasurai@ubuntu:~$ sudo apt install docker.iosasurai@ubuntu:~$ docker versionClient: Version: 19.03.2 API version:
阅读更多

MySQL查询卡死、无返回结果问题解决

现象

①在Navicat中,修改表结构,点击保存,然后发现Navicat卡住,无法正常退出,且MySQL无数据返回。
②在任务管理器中强制关闭了Navicat后,重复在Navicat中尝试几次,结果仍然一样。
③在MySQL CLI中进行select查询,同样卡住。

分析

起初认为是网络问题,但是想到可能是被堵塞住了。

解决

查询MySQL中的进程:show processlist

打开正在进行中的进程列表,发现有Waiting for table metadata lock,所以初步判定是因为某个操作被堵塞,然后后续操作无法执行,从而引起了这个问题。

从网上的资料看来,可能的原因是有未提交事物,阻塞DDL,继而阻塞所有同表的后续操作;结合自己对此数据库的操作,初步认为是在自己的小项目里面,可能存在上述情况。

查看未提交的事务:select trx_state, trx_started, trx_mysql_thread_id, trx_query from information_schema.innodb_trx\G

执行后,发现确实存在未提交的事务。

kill掉未提交的事务,返回到Navicat,发现 之前卡住的操作已完成

【参考】
https://blog.csdn.net/benben683280/article/details/78799010
https://blog.csdn.net/u013235478/article/details/68062939
https://www.cnblogs.com/digdeep/p/4892953.html

解决web端登录时等待过久并偶尔抛出事务相关异常

问题描述

在这里插入图片描述

分析

登录函数中有一个事务,如下:
在这里插入图片描述
事务里面有一个有可能操作比较耗时的过程:
在这里插入图片描述
在新增登录日志的时候,获取用户的ip。
在这里插入图片描述
具体干了啥不重要,重要的是发了一个http请求,并且是串行的,所以这个请求比较耗时的可能是很大的,并且具备不确定性因素。
在这里插入图片描述

反思

TransactionRollbackException的文档注释为:

This exception indicates that the transaction associated with processing of the request has been rolled back, or marked to roll back. Thus the requested operation either could not be performed or was not performed because further computation on behalf of the transaction would be fruitless

可能的过程为:线程1进入事务、然后进行了一次update操作,获得了一个排他锁,然后被卡在了获取ip的那个地方,即此事务持有着排他锁,然后还长时间不结束(50s+),然后线程2也进入了事务,此时在进行update的时候,需要等待线程1释放排它锁,在50秒过后,仍未获取到锁,此时获取锁时间超过了预设,抛出上述异常。

解决

规避潜在的耗时操作。但是由于此服务没人维护,因此通过本地编译,然后拉包替换相应class文件,再上传到服务器的方式进行修改。

复现

查看获取锁的超时阀值:

1
SHOW VARIABLES LIKE '%timeout%';

输出如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
+-----------------------------+----------+
| Variable_name | Value |
+-----------------------------+----------+
| connect_timeout | 10 |
| delayed_insert_timeout | 300 |
| have_statement_timeout | YES |
| innodb_flush_log_at_timeout | 1 |
| innodb_lock_wait_timeout | 50 |
| innodb_rollback_on_timeout | OFF |
| interactive_timeout | 28800 |
| lock_wait_timeout | 31536000 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| rpl_stop_slave_timeout | 31536000 |
| slave_net_timeout | 60 |
| wait_timeout | 28800 |
+-----------------------------+----------+
13 rows in set (0.01 sec)

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// --------------------------Controller------------
/**
* 测试web端登录锁表
*/
@GetMapping("/hotline/test")
public void testSomeThing() throws InterruptedException {
testService.doSomething();
}
// ----------------------------Service----------------
@Service
public class TestService {

@Autowired
private BizConfMapper confMapper;

@Transactional(rollbackFor = Exception.class)
public void doSomething() throws InterruptedException {
// 共享锁
BizConf conf = confMapper.selectByPrimaryKey(0);
// 排它锁
confMapper.updateByPrimaryKey(conf);
// 等待让下个线程超时,最起码要大于50
Thread.sleep(60000);
}
}

日志输出与项目中出现的错误信息基本一致,如下:
在这里插入图片描述
@Transactional注解中加入timeout后,报错不一样,但是阔以理解为spring框架为我们抛出了异常。如下:
在这里插入图片描述

后记

其中对我理解这种现象有很大帮助的资料为这一张图,它让我明白了锁与事务之间的关系。
在这里插入图片描述
参考:
https://segmentfault.com/a/1190000014133576

MySQL中插入emoji表情报错的问题解决方案

操作:在内容中输入表情,然后点击查询,报错。
在这里插入图片描述
其中这个请求的处理代码如下:
在这里插入图片描述
请求的内容为:

1
/feedbacks?page=1&size=20&content=%F0%9F%98%AF%F0%9F%98%A2

日志如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
2018-12-21 10:11:49,731 [http-nio-8889-exec-10]  INFO c.h.d.a.SystemAdvice - execute method : getFeedbacks
2018-12-21 10:11:49,733 [http-nio-8889-exec-10] ERROR c.h.d.a.SystemAdvice - aspect execute error :
org.springframework.jdbc.UncategorizedSQLException:
### Error querying database. Cause: java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
### The error may exist in class path resource [mappers/BizFeedbackMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT count(0) FROM biz_feedback WHERE content LIKE ? AND deleted = ?
### Cause: java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
; uncategorized SQLException; SQL state [HY000]; error code [1267]; Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation
'like'; nested exception is java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:89)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
at com.sun.proxy.$Proxy77.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
at com.sun.proxy.$Proxy101.getSortedResultByConditionList(Unknown Source)
at com.haylion.dynamicbus.service.FeedbackService.getFeedbacks(FeedbackService.java:40)
at com.haylion.dynamicbus.service.FeedbackService$$FastClassBySpringCGLIB$$298f5809.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
at com.haylion.dynamicbus.advice.SystemAdvice.doAroundAdvice(SystemAdvice.java:44)
at sun.reflect.GeneratedMethodAccessor348.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at com.haylion.dynamicbus.service.FeedbackService$$EnhancerBySpringCGLIB$$ab8db9b2.getFeedbacks(<generated>)
at com.haylion.dynamicbus.controller.FeedbackController.getFeedbacks(FeedbackController.java:69)
at com.haylion.dynamicbus.controller.FeedbackController$$FastClassBySpringCGLIB$$825dd925.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at com.haylion.dynamicbus.controller.FeedbackController$$EnhancerBySpringCGLIB$$f311ce89.getFeedbacks(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:890)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.haylion.dynamicbus.facade.filter.TraceCopyFilter.doFilter(TraceCopyFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1197)
at com.alibaba.druid.pool.DruidPooledPreparedStatement.execute(DruidPooledPreparedStatement.java:498)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
at com.haylion.dynamicbus.interceptor.sql.MyPageInterceptor.executeAutoCount(MyPageInterceptor.java:211)
at com.haylion.dynamicbus.interceptor.sql.MyPageInterceptor.intercept(MyPageInterceptor.java:114)
at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
at com.sun.proxy.$Proxy154.query(Unknown Source)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at sun.reflect.GeneratedMethodAccessor116.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
... 90 common frames omitted
2018-12-21 10:11:49,734 [http-nio-8889-exec-10] ERROR c.h.d.f.e.ExceptionHandle - Exception for handle
org.springframework.jdbc.UncategorizedSQLException:
### Error querying database. Cause: java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
### The error may exist in class path resource [mappers/BizFeedbackMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT count(0) FROM biz_feedback WHERE content LIKE ? AND deleted = ?
### Cause: java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
; uncategorized SQLException; SQL state [HY000]; error code [1267]; Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation
'like'; nested exception is java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:89)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
at com.sun.proxy.$Proxy77.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
at com.sun.proxy.$Proxy101.getSortedResultByConditionList(Unknown Source)
at com.haylion.dynamicbus.service.FeedbackService.getFeedbacks(FeedbackService.java:40)
at com.haylion.dynamicbus.service.FeedbackService$$FastClassBySpringCGLIB$$298f5809.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
at com.haylion.dynamicbus.advice.SystemAdvice.doAroundAdvice(SystemAdvice.java:44)
at sun.reflect.GeneratedMethodAccessor348.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at com.haylion.dynamicbus.service.FeedbackService$$EnhancerBySpringCGLIB$$ab8db9b2.getFeedbacks(<generated>)
at com.haylion.dynamicbus.controller.FeedbackController.getFeedbacks(FeedbackController.java:69)
at com.haylion.dynamicbus.controller.FeedbackController$$FastClassBySpringCGLIB$$825dd925.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at com.haylion.dynamicbus.controller.FeedbackController$$EnhancerBySpringCGLIB$$f311ce89.getFeedbacks(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:890)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.haylion.dynamicbus.facade.filter.TraceCopyFilter.doFilter(TraceCopyFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1197)
at com.alibaba.druid.pool.DruidPooledPreparedStatement.execute(DruidPooledPreparedStatement.java:498)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
at com.haylion.dynamicbus.interceptor.sql.MyPageInterceptor.executeAutoCount(MyPageInterceptor.java:211)
at com.haylion.dynamicbus.interceptor.sql.MyPageInterceptor.intercept(MyPageInterceptor.java:114)
at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
at com.sun.proxy.$Proxy154.query(Unknown Source)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at sun.reflect.GeneratedMethodAccessor116.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
... 90 common frames omitted
2018-12-21 10:11:49,734 [http-nio-8889-exec-10] INFO c.h.d.f.a.ResponseAdvice - Trace log is ====> {"url":"/bus/feedbacks","httpMethod":"GET","reqHeader":{"x-real-ip":
"10.10.0.195","referer":"https://xxxxxxx.cn/","accept-language":"zh,en;q=0.9,ja;q=0.8,zh-TW;q=0.7,fr;q=0.6","host":"10.10.0.103","connection":"close","x-forwar
ded-for":"10.10.0.195","userid":"435","accept-encoding":"gzip, deflate, br","accept":"application/json, text/plain, */*","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win6
4; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36","token":"67f7df9448dd691c71f57bcb95891bcf"},"reqParams":"page=1&size=20&content=%F0%9F%
98%AF%F0%9F%98%A2","requestBody":"","respParams":"{\"code\":500,\"message\":\"system is busy\",\"data\":{}}","startTime":1545358309731,"spendTime":3}

从网上搜了一个解决方案,生效了:
在这里插入图片描述
然后重启MySQL,service mysql restart
链接地址为:https://dba.stackexchange.com/questions/89355/unable-to-insert-utf8mb4-characters-in-mysql-5-6

在这里插入图片描述
以下关于MySQL中的字符相关的知识来自链接:https://www.cnblogs.com/chyingp/p/mysql-character-set-collation.html

通过分析,得出一下结论:
like里面填写的数据的编码格式为utf8,为character_set_server的值,而表里面的编码为utf8mb4,所以他们的值的字符序列是不一样的,因此造成了上述问题的出现。所以解决的办法是将服务器的字符改成utf8mb4,这样like的值就是utf8mb4编码格式,字符序就与表中的字段一致,问题解决。

CentOS7中安装MySQL的详细过程以及配置

首先使用yum安装mariadb,它是MySQL的一个分支。

1
2
sudo yum install -y mariadb-server # 安装mariadb
rpm -qa | grep mariadb # 查看mariadb已安装的相关包

要连上数据库,就得先启动它。所以先尝试下面的启动命令。

1
2
3
4
systemctl start mariadb.service #启动服务
systemctl enable mariadb.service #设置开机启动
systemctl restart mariadb.service #重新启动
systemctl stop mariadb.service #停止MariaDB

启动后,在命令行中输入mysql -u root -proot密码默认为空,直接按回车即可。此时的密码为空,先设置一个密码,方法有多种,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
1.用root 进入mysql后
mysql>set password =password('你的密码');
# 或者
mysql>set password for root@localhost = password('hellomysql');
mysql>flush privileges;

2.使用GRANT语句
mysql>grant all on *.* to 'root'@'localhost' IDENTIFIED BY '你的密码'with grant option ;
mysql>flush privileges;

3.进入mysql库修改user表
mysql>use mysql;
mysql>update user set password=password('你的密码') where user='root';
mysql>flush privileges;

如果要从局域网中访问数据库,那么需要紧接着进行下面的配置:

1
2
3
4
5
6
# 选择mysql这个数据库
use mysql;
# 这一句执行完可能会报错,不用管它。
update user set host = '%' where user = 'root';
# 刷新配置
FLUSH PRIVILEGES;

接下来配置防火墙,将3306端口开放:

1
2
sudo firewall-cmd --add-port=3306/tcp --permanent # 开放3306端口
sudo firewall-cmd --reload # 重新读入配置

这个时候应该就可以通过局域网访问了。

如果忘记了root密码怎么办?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 首先,先关闭mysql原来的服务:
systemctl stop mariadb.service

# 开启mysql的安全模式
sudo mysqld_safe --skip-grant-tables&
# 进入mysql,直接修改表中root的密码
mysql>update user set password=password("hellomysql") where user='root';
mysql>flush privileges; # 刷新权限
mysql>exit;
# 然后关闭mysql的安全模式。这里只需要将之前开启的mysql进程关闭掉即可。
ps aux | grep mysqld # 列出mysql的进程信息
sudo kill -s 9 xxxx # 强制关闭进程

# 重新打开mysql服务
systemctl start mariadb.service

关于MySQL中的用户与host
这里写图片描述
仔细观察这个表,我们可以发现同一个root,可能对于不同的host。换个角度,也就是说,同一个用户的不同host,我们可以设置不同的权限以及密码。这是一个在解决了局域网中不能访问数据库这个问题后,本地访问数据库出现了不能访问的情况。不能用密码访问,但是可以无密码访问,无密码访问后,没有任何修改的权限。仔细看上表中的第5行,之前不是这样,上图是被我修改过之后,正常运行的截图。未修改之前,User那一栏是空的,Password也是空的,其它三项权限都是N,所以也不难理解为什么会出现上述的情况。后面手动修改成上面的数据后,变可以以“root+密码”进行访问,并且有相应的权限。

MySQL中的常用关键字

很久不用MySQL,感觉又是一个新的玩意儿了,写起SQL语句来感觉好陌生,确实是很久了!

distinct

查询出某个字段不重复的记录。可用distinct来返回不重复字段的条数count(distinct id)

limit

记得这个可以用来做分页。它后面可以接受一个或两个数字参数。参数必须是一个整数常量。如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目

1
2
3
4
5
6
7
8
//初始记录行的偏移量是 0(而不是 1):
mysql> SELECT * FROM table LIMIT 5,10; //检索记录行6-15

//为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1
mysql> SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last

//如果只给定一个参数,它表示返回最大的记录行数目。换句话说,LIMIT n 等价于 LIMIT 0,n:
mysql> SELECT * FROM table LIMIT 5; //检索前 5 个记录行

limit的效率高?

常说的Limit的执行效率高,是对于一种特定条件下来说的:即数据库的数量很大,但是只需要查询一部分数据的情况。高效率的原理是:避免全表扫描,提高查询效率。比如:每个用户的email是唯一的,如果用户使用email作为用户名登陆的话,就需要查询出email对应的一条记录。
SELECT * FROM t_user WHERE email=?;
上面的语句实现了查询email对应的一条用户信息,但是由于email这一列没有加索引,会导致全表扫描,效率会很低。
SELECT * FROM t_user WHERE email=? LIMIT 1;
加上LIMIT 1,只要找到了对应的一条记录,就不会继续向下扫描了,效率会大大提高。

limit的效率低?

在一种情况下,使用limit效率低,那就是:只使用limit来查询语句,并且偏移量特别大的情况。做以下实验:
语句1:
select * from table limit 150000,1000;
语句2:
select * from table while id>=150000 limit 1000;
语句1为0.2077秒;语句2为0.0063秒。两条语句的时间比是:语句1/语句2=32.968

比较以上的数据时,我们可以发现采用where…limit….性能基本稳定,受偏移量和行数的影响不大,而单纯采用limit的话,受偏移量的影响很大,当偏移量大到一定后性能开始大幅下降。不过在数据量不大的情况下,两者的区别不大。所以应当先使用where等查询语句,配合limit使用,效率才高。在sql语句中,limt关键字是最后才用到的。以下条件的出现顺序一般是:**where->group by->having-order by->limit**

OFFSET

为了与 PostgreSQL 兼容,MySQL 也支持句法: LIMIT # OFFSET #。经常用到在数据库中查询中间几条数据的需求比如下面的sql语句:

selete * from testtable limit 2,1;
selete * from testtable limit 2 offset 1;

注意:
1.数据库数据计算是从0开始的
2.offset X是跳过X个数据,limit Y是选取Y个数据
3.limit X,Y 中X表示跳过X个数据,读取Y个数据

这两个都是能完成需要,但是他们之间是有区别的:
①是从数据库中第三条开始查询,取一条数据,即第三条数据读取,一二条跳过
②是从数据库中的第二条数据开始查询两条数据,即第二条和第三条。

UNION & UNION ALL

union all是直接连接,取到得是所有值,记录可能有重复 union 是取唯一值,记录没有重复。

1、UNION 的语法如下:
[SQL 语句 1]
UNION
[SQL 语句 2]

2、UNION ALL 的语法如下:
[SQL 语句 1]
UNION ALL
[SQL 语句 2]

效率

UNION和UNION ALL关键字都是将两个结果集合并为一个,但这两者从使用和效率上来说都有所不同。

1、对重复结果的处理:UNION在进行表链接后会筛选掉重复的记录,Union All不会去除重复记录。

2、对排序的处理:Union将会按照字段的顺序进行排序;UNION ALL只是简单的将两个结果合并后就返回。

从效率上说,UNION ALL 要比UNION快很多,所以,如果可以确认合并的两个结果集中不包含重复数据且不需要排序时的话,那么就使用UNION ALL。

简单应用

将一个表的内容弄成两份到一个输出中:

1
2
3
4
select * from
(select * from players) b
UNION all
(select * from players) ;

join相关

left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录
right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录
inner join(等值连接) 只返回两个表中联结字段相等的行

参考:
https://www.cnblogs.com/acm-bingzi/p/msqlLimit.html

MySQL中的日期操作

获取当前时间

  • now()

    1
    2
    3
    4
    5
    6
    7
    mysql> select now();
    +---------------------+
    | now() |
    +---------------------+
    | 2018-07-26 15:58:46 |
    +---------------------+
    1 row in set (0.00 sec)
  • sysdate()

    1
    2
    3
    4
    5
    6
    7
    mysql> select sysdate()
    +---------------------+
    | sysdate() |
    +---------------------+
    | 2018-07-26 15:59:19 |
    +---------------------+
    1 row in set (0.00 sec)

两者之间的区别在于:**sysdate()是实时获取的**。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mysql> select now(), sleep(3), now();
+---------------------+----------+---------------------+
| now() | sleep(3) | now() |
+---------------------+----------+---------------------+
| 2018-07-26 16:00:14 | 0 | 2018-07-26 16:00:14 |
+---------------------+----------+---------------------+
1 row in set (3.00 sec)

mysql> select sysdate(), sleep(3), sysdate();
+---------------------+----------+---------------------+
| sysdate() | sleep(3) | sysdate() |
+---------------------+----------+---------------------+
| 2018-07-26 16:00:30 | 0 | 2018-07-26 16:00:33 |
+---------------------+----------+---------------------+
1 row in set (3.00 sec)
  • current_timestamp, current_timestamp()
1
2
3
4
5
6
7
mysql> select current_timestamp, current_timestamp();
+---------------------+---------------------+
| current_timestamp | current_timestamp() |
+---------------------+---------------------+
| 2018-07-26 16:04:01 | 2018-07-26 16:04:01 |
+---------------------+---------------------+
1 row in set (0.00 sec)

日期、时间转换

感觉时间与日期这块有挺多操作的,包括与字符串的相互转换等。

日期/时间转字符串

  • date_format()/time_format()将日期/时间转换成字符串
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    mysql> select date_format('2018-7-26 16:05:11', '%Y%m%d%H%i%s')
    +---------------------------------------------------+
    | date_format('2018-7-26 16:05:11', '%Y%m%d%H%i%s') |
    +---------------------------------------------------+
    | 20180726160511 |
    +---------------------------------------------------+
    1 row in set (0.00 sec)

    mysql> select time_format('16:05:11', '%H%i%s');
    +-----------------------------------+
    | time_format('16:05:11', '%H%i%s') |
    +-----------------------------------+
    | 160511 |
    +-----------------------------------+
    1 row in set (0.00 sec)
  • str_to_date() 将字符串转成日期类型。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    mysql> select str_to_date('07/26/2018', '%m/%d/%Y');
    +---------------------------------------+
    | str_to_date('07/26/2018', '%m/%d/%Y') |
    +---------------------------------------+
    | 2018-07-26 |
    +---------------------------------------+
    1 row in set (0.00 sec)

    mysql> select str_to_date('2018/7/26 16:23:33','%Y/%m/%d %H:%i:%s');
    +-------------------------------------------------------+
    | str_to_date('2018/7/26 16:23:33','%Y/%m/%d %H:%i:%s') |
    +-------------------------------------------------------+
    | 2018-07-26 16:23:33 |
    +-------------------------------------------------------+
    1 row in set (0.00 sec)

日期时间计算函数

为日期增加一个时间间隔:date_add()

1
2
3
4
5
6
7
8
9
10
11
12
13
set @dt = now();

select date_add(@dt, interval 1 day); -- add 1 day
select date_add(@dt, interval 1 hour); -- add 1 hour
select date_add(@dt, interval 1 minute); -- ...
select date_add(@dt, interval 1 second);
select date_add(@dt, interval 1 microsecond);
select date_add(@dt, interval 1 week);
select date_add(@dt, interval 1 month);
select date_add(@dt, interval 1 quarter);
select date_add(@dt, interval 1 year);

select date_add(@dt, interval -1 day); -- sub 1 day

为日期减去一个时间间隔:date_sub()
日期、时间相减函数:datediff(date1,date2), timediff(time1,time2)