目录
1、单表操作
一、查询表数据
a、查询b表有 但是a表没有的name(单字段查询)的数据
select name from b where name not in(select name from a);
b、查询b表有 但是a表没有的id,name(多字段查询)的数据
select id,name from b where (id,name) not in(select id,name from a);
select * from b where (id,name) not in(select * from a);
=================================================
二、获取数据表字段
获取数据表的字段
select column_name from information_schema.columns where table_schema='your databasename' and table_name='your tablename';
=================================================
三、复制新表
a、创建和b表字段一样的a表(仅仅复制结构)
create table a like b;
b、创建和b表字段一样的a表(复制结构和数据)
create table a select * from b;
=================================================
四、插入原表数据到另一个表中
a、向a表插入b表中所有的数据(前提是a,b表字段一样,而且a表存在)
insert in to a select * from b;
b、向a表插入b表中符合条件的数据(where)
insert into a select * from b where id>10;
c、向a表插入b表中指定字段的数据(前提是a表中有这些字段)
insert into a (id,name) select id,name from b;
2、多表查询操作
=================================================
以下是测试的两张表信息:
学生表(student): 分数表(sgrade):
五、内连接 (inner join)
select * from student inner join sgrade on sid=studentID;
一般用的比较多的是内连接,来进行多表关联查询。
=================================================
六、左连接(left join)
select * from student left join sgrade on sid=studentID; (左连接以左表为基准)
select * from sgrade left join student on sid=studentID;
可以看到,不同的基准表采用左连接后,查询到的结果是不一致的。
=================================================
七、右连接(right join)
select * from student right join sgrade on sid=studentID; (右连接以右表为基准)
3、查询mysql指定行数
显示5到10行的记录,即查询6行记录: select * from tablename limit 4,6;
显示第6行的记录: select * from tablename limit 5,1;
查询前n行记录: select * from tablename limit n;
查询后n行记录: select * from tablename order by id desc limit n;
4、删除id字段 指定行数间的记录
delete from table where id in (select id from (select id from table limit m,n) as temp)
人生苦短,总结不易,如果这篇文章可以帮助到你,请轻轻移动一下鼠标,把它顶(赞)起来,分享给更多的需要的伙伴。