MySQL应用异常问题解决

MySQL错误:Every derived table must have its own alias


 派生表都必须有自己的别名

一般在多表查询时,会出现此错误。

因为,进行嵌套查询的时候子查询出来的的结果是作为一个派生表来进行上一级的查询的,所以子查询的结果必须要有一个别名,

把MySQL语句改成:select count(*) from (select * from ……) as total;

问题就解决,虽然只加了一个没有任何作用的别名total,但这个别名是必须的

select name1 name, java, jdbc, hibernate,total
  from (select sc1.name name1, sc1.mark java
   from student_course2 sc1
   where sc1.course='java') as a,
   (select sc2.name name2, sc2.mark jdbc
   from student_course2 sc2
   where sc2.course='jdbc') as b,
   (select sc3.name name3, sc3.mark hibernate
   from student_course2 sc3
   where sc3.course='hibernate') as c,
 (select sc4.name name4,sum(sc4.mark) total
 from student_course2 sc4 group by sc4.name) as d
  where name1=name2 and name2=name3 and name3=name4 order by total ASC; 

结果正确:

+----------+------+------+-----------+-------+
| name     | java | jdbc | hibernate | total |
+----------+------+------+-----------+-------+
| wangwu   |   40 |   30 |        20 |    90 |
| lisi     |   70 |   60 |        50 |   180 |
| zhangsan |  100 |   90 |        80 |   270 |
+----------+------+------+-----------+-------+
3 rows in set (0.02 sec)

 

Error Code: 1045. Access denied for user 'test'@'%' (using password: YES)


使用MySQL的select * into outfile ‘/tmp/rs.txt’ from tb_name来导出结果时遇到这个问题,

当前用户虽然拥有全部权限,但是file权限需要单独赋予,使用root用户执行:

grant file on *.* to test@localhost;

 

Error Code: 1093. You can't specify target table 'mytable' for update in FROM clause


在使用update或者delete语句时,在where条件里面加入的子查询导致的。

这时候可以将该表再嵌套一层,即“(select * from table) tt”,得出一个临时的结果集,
在这个结果集上操作就可以了。

delete from mytable where mytable.id not in
(SELECT tt.id FROM (SELECT * FROM mytable) tt where tt.siteid=22 );  

 

Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode,toggle the option in Preferences -> SQL Editor and reconnect.


解决办法是关闭安全模式:

SET SQL_SAFE_UPDATES = 0;  

注意如果你是使用MySQL Workbench,还需要配置一下软件的首选项。
因为MySQL Workbench的默认的安全设置是不能批量更新表的。
当要执行的SQL语句是进行批量更新或者删除的时候就会提示这个错误。
解决方法如下:
打开Workbench的菜单[Edit]->[Preferences...]
切换到[SQL Editor]页面
把[Forbid UPDATE and DELETE statements without a WHERE clause (safe updates)]之前的对勾去掉
点击[OK]按钮


MySQL插入时使用当前时间


NOW()函数以`'YYYY-MM-DD HH:MM:SS'返回当前的日期时间,可以直接存到DATETIME字段中。

CURDATE()以’YYYY-MM-DD’的格式返回今天的日期,可以直接存到DATE字段中。
CURTIME()以’HH:MM:SS’的格式返回当前的时间,可以直接存到TIME字段中。

insert into table (id ,time) values('1',NOW() )

Error Code: 1100. Table 'mytable' was not locked with LOCK TABLES


 我在插入前执行了

LOCK TABLES `mytable` WRITE;

重新解锁即可:

UNLOCK TABLES;

  

原文地址:https://www.cnblogs.com/binyue/p/5145530.html