1、 建users表
create table users (id int primary key auto_increment,nikename varchar(20) not null unique,password varchar(100) not null,address varchar(200));
2、建articles表,在建表时设置外键
create table articles (id int primary key auto_increment,content longtext not null,userid int,constraint foreign key (userid) references users(id) on delete set null);
2.1 、建articles表,建表时不设置外键
create table articles (id int primary key auto_increment,content longtext not null,userid int);
2.2、 给articles表设置外键
alter table articles add constraint foreign key (userid) references users(id) on delete set null;
3、向users表中插入数据,同时插入多条
insert into users (id,nikename,password,address) values (1,'lyh1','1234',null),(10,'lyh22','4321','湖北武汉'), (null,'lyh333','5678','北京海淀');
4、 向article中插入三条数据
insert into articles (id,content,userid) values (2,'hahahahahaha',11),(null,'xixixixixix',10),(13,'aiaiaiaiaiaiaiaiaiaiaiaia',1),(14,'hohoahaoaoooooooooo',10);
5、进行多表查询,选择users表中ID=10的用户发布的所有留言及该用户的所有信息
select articles.id,articles.content,users.* from users,articles where users.id=10 and articles.userid=users.id order by articles.id desc;
6、查看数据库引擎类型
show create table users;
7、修改数据库引擎类型
alter table users engine=MyISAM; ---因为users表中ID被设置成外键,执行此句会出错
8、 同表查询,已知一个条件的情况下.查询ID号大于用户lyh1的ID号的所有用户
select a.id,a.nikename,a.address from users a,users b where b.nikename='lyh1' and a.id>b.id;
------也可写成
select id,nikename,address from users where id>(select id from users where nikename='lyh1');
阅读(903) | 评论(0) | 转发(0) |