MySQL插入、更新与删除数据习题

第一例

image.png

mysql> CREATE TABLE food(
-> id INT(10) PRIMARY KEY NOT NULL UNIQUE AUTO_INCREMENT,
-> name VARCHAR(20) NOT NULL,
-> company VARCHAR(30) NOT NULL,
-> price FLOAT,
-> produce_time YEAR,
-> validity_time INT(4),
-> address VARCHAR(50)
-> );

1.将下边的记录插入到food表中


image.png

第一种方法不指定具体的字段:
INSERT INTO food VALUES(1,'AA饼干','AA饼干厂', 2.5 ,'2008', 3 ,'北京');

第二种方法是依次指定food表的字段:
INSERT INTO food( id, name, company, price, produce_time, validity_time, address)
VALUES(2,'CC牛奶','CC牛奶厂', 3.5 ,'2009', 1 ,'河北');

第三种方法是同时插入多条记录:
INSERT INTO food VALUES
(NULL,'EE果冻','EE果冻厂', 1.5 ,'2007', 2 ,'北京') ,
(NULL,'FF咖啡','FF咖啡厂', 20 ,'2002', 5 ,'天津') ,
(NULL,'GG奶糖','GG奶糖', 14 ,'2003', 3 ,'广东');

2.将“CC牛奶厂”的厂址(address)改为“内蒙古”,并且将价格改为3.2
mysql> UPDATE food SET address='内蒙古',price=3.2 WHERE name='CC牛奶';
3.将厂址在北京的公司保质期(validity_time)都改为5年
mysql> UPDATE food SET validity_time=5 WHERE address='北京';

4.删除过期食品的记录。若当前时间-生产年份(produce_time)>保质期(validity_time),则视为过期食品
mysql> DELETE FROM food WHERE validity_time<(2013-produce_time);

5.删除厂址为北京的食品的记录
mysql> DELETE FROM food WHERE address='北京';

第二例

Teacher表的定义


image.png

1.向teacher表中插入数据


image.png

INSERT INTO teacher VALUES(1, 1001, '张三','男' ,'1984-11-08' ,'北京市昌平区'),
(NULL, 1002, '李四','女' ,'1970-01-21' ,'北京市海淀区') ,
(NULL, 1003, '王五','男' ,'1976-10-30' ,'北京市昌平区') ,
(NULL, 1004, '赵六','男' ,'1980-06-05' ,'北京市顺义区') ;

2.更新id为1的记录,将生日(birthday)改为“1982-11-08”
mysql> UPDATE teacher SET birthday='1982-11-08' WHERE id=1;

3.将性别(sex)为“男”的记录的家庭住址(address)都变为“北京市朝阳区”
mysql> UPDATE teacher SET address='北京市朝阳区' WHERE sex='男';

4.删除教工号(num)为1002的记录删除
mysql> DELETE FROM teacher WHERE num=1002;

你可能感兴趣的:(MySQL插入、更新与删除数据习题)