MySQL 练习

1.创建留言数据库: messagedb;

mysql> create database messagedb charset = utf8;

2.在messagedb数据库中创建留言表message,结构如下:

表名

message

留言信息表

序号

字段名称

字段说明

类型

属性

备注

1

id

编号

int

非空

主键,自增1

2

title

标题

varchar(32)

非空

 

3

author

作者

varchar(16)

可以空

 

4

addtime

留言时间

datetime

非空

 

5

content

留言内容

text

非空

 

6

isdelete

是否删除

char(1)

非空

默认值 0

CREATE TABLE `message` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(32) NOT NULL,
  `author` varchar(16) DEFAULT NULL,
  `addtime` datetime DEFAULT NULL,
  `content` text,
  `status` char(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

3.在留言表最后添加一列状态(status  char(1)  默认值为0)

4.修改留言表author的默认值为’youku’,设为非空

5.删除message表中的isdelete字段

6.为留言表添加>5条测试数据

INSERT INTO `message` VALUES ('1', '介绍', '大雄', '2017-02-14 09:59:37', '哥不是一匹好马,但也不是一头普通的毛驴', '0');
INSERT INTO `message` VALUES ('2', '叮当猫', '熊熊', '2016-02-16 09:59:44', '你牙缝里有韭菜,扣出来贼哥吃', '0');
INSERT INTO `message` VALUES ('3', '花花', '苗苗', '2017-05-28 09:59:52', '苗苗问花花:卖萌是褒义词还是贬义词?', '0');
INSERT INTO `message` VALUES ('4', '霞哥', '大雄', '2017-08-29 09:59:57', '斗战色佛', '0');
INSERT INTO `message` VALUES ('5', '晨晨', '逗比', '2010-06-22 10:00:03', '你笑起来像一朵菊花,菊花残,man腚伤', '0'); 

7. 要求将id值大于3的信息中author字段值改为admin

update message set author='admin' where id>3;

8. 删除id号为4的数据。

delete from message where id=4;
  • 为留言表添加>15条测试数据,要求分三个用户添加
  • INSERT INTO `message` VALUES ('6', '晨晨', '逗比', '2010-06-22 10:00:03', '你笑起来像一朵菊花,菊花残,man腚伤', '1');
  • 查询所有留言信息
  • select * from message;
  • 查询某一用户的留言信息。
  • select * from message where author='用户名';
  • 查询所有数据,按时间降序排序。
  • select * from message order by addtime desc;
  • 获取id在2到6之间的留言信息,并按时间降序排序
  • select * from message where id>2 and id<6 order by addtime desc;
  • 统计每个用户留了多少条留言,并对数量按从小到大排序。
  • select author,COUNT(id) as '留言条数' FROM message GROUP BY author ORDER BY COUNT(id) ASC;
  • 将id为8、9的两条数据的作者改为’doudou’.
  • update message set author='doudou' where id=8 or id=9;
  • 取出最新的三条留言。
  • select * from message order by addtime desc limit 3;
  • 查询留言者中包含”a”字母的留言信息,并按留言时间从小到大排序
  • select * from message where author like '%a%' order by 'addtime' desc;
  • 删除”作者”重复的数据,并保留id最大的一个作者
  • delete from message where author in(
        select author from (select author from message group by author having count(1)>1) a
    )
    and id not in(
        select id from (select max(id) id from message group by author having count(1)>1) b
    )
原文地址:https://www.cnblogs.com/wilson-wu/p/8479171.html