注:所有的下划线+斜体语句都是非必须语句
元组新增Insert:
单组新增SQL语句:
Insert Into 表名(列名1, 列名2, ……)
Values(值1, 值2, ……);
批数据新增SQL语句:
Insert Into 表名(列名1, 列名2, ……)
子查询;
其中子查询即Select-from-where语句
例子:新建Table:SCt(S#, C#, Score),将检索到的成绩及格同学的记录新增到该表中
Insert Into SCt(S#, C#, Score) Select S#, C#, Score From SC Where Score>=60;
还有更复杂的“查询后插入到新表中”的语句,例如可以将中间结果存储成表等等
例如新建Table: St(S#, Sname, avgScore),将检索到的同学的平均成绩新增到该表中
Insert Into St(Sc, Sname, avgScore) Select Sc, Sname, Avg(Score) From Student, SC Where Student.Sc = SC.Sc Group by Student.Sc ;
新建一张表sctemp,它是表sc的复制:
create table sctemp like sc; insert into sctemp (select * from sc);
元组删除Delete:
SQL语句:
Delete from 表名 where 条件表达式
- 如果没有后面的where语句就相当于删除整张表
例子:删除98030101号同学所选的所有课程
Delete From SC Where S#='98030101';
还有更复杂的条件控制的删除语句等,例如删除四门课都不及格的学生数据:
Delete From Student Where Sc in (Select Sc From SC Where Score<60 Group by Sc Having Count(*)>=4);
元组更新Update:
SQL语句:
Update 表名
set 列名1 = 表达式1 或 (子查询1), 表达式2 或 (子查询2)……
where 条件表达式
- 如果没有后面的where语句就相当于更新所有元组
例如将所有教师工资上调5%:
Update Teacher Set Salary = Salary*1.05;
当然还有更复杂的条件控制的更新语句
例如①当某同学001号课的成绩低于该课程平均成绩时,将该同学该门课成绩提高5%
update sc set score = score*1.05 where ct = '003' and score < some(select avg(score) from sctemp where ct = '003');
其中sctemp是表sc的复制,注意可能不能直接使用sc,会出现错误提示:1093 You can't specify target table 'sc' for update in FROM clause,意思就是不能在同一语句中更新select出的同一张表元组的属性值;解决方法:如上,或者将select出的结果通过中间表再select一遍即可
②根据学生选课情况 sc(st, ct, score),更新每个同学的选课数量 infer(st, sex, name, num)
附录:MySQL解除输入的安全模式:
应对错误提示: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 Queries and reconnect.
产生原因:MySql运行在safe-updates模式下,该模式会导致非主键条件下无法执行update或者delete命令
解决方法:
查看安全模式是否打开:how variables like 'SQL_SAFE_UPDATES'
更新安全模式:set SQL_SAFE_UPDATES = 1/0