-- 连接:外连接,内连接 两个表之间
外连接:right join left join
-- left join 左标为主 一般以值少的为主 select * from table1 left join table2 on table1.id = table2.id; -- right join 右标为主 一般以值少的为主 select * from table1 right join table2 on table1.id = table2.id;
内连接:join
-- join 不给条件 相当于select * from table1,table2; 会产生笛卡儿积 select * from table1 join table2 ; -- join on +条件 一对一 select * from table1 join table2 on table1.id=table2.id;
Copy表
-- 建新表是copy旧表数据 -- 复制所有 create table new select * from old; -- 将旧表的某些字段导入另一张表 insert into new(字段1,2,3...) select 字段1,2,3... from old
分组:group by
-- 创建一个测试表 create table test( id int primary key auto_increment, name varchar(15), age int ); insert into test(name,age) values('tj',18),('th',15),('tr',10); --条件 查询 -- select * from test; select * from test where age >12 && name = 'tj'; select * from test where age >12 || name = 'tj'; -- 取别名 select name as '名字',age as '年龄' from test; -- 取别名关键字as 可不写 --查询行数 -- limit select * from test limit 2; -- 当id 有自增长auto_increment,比如id 默认值到了5,删除了这五条数据,插入吓一跳数据id值默认+1成了6 -- truncate 可初始化自增长id 为1. -- 分组 group by -- 几个字节对应几个分组字节 select 字节1,字节2 from table group by 字节1,字节2. insert into test(name,age) values('tj1',18),('th1',15),('tr1',10); select age from test group by age; -- 分组+ 统计次数,最大值,最小值,和,平均值 select age,count(*),max(age),min(age),sum(age),avg(age) from test group by age; -- having +条件 select age,count(*),max(age),min(age),sum(age),avg(age) from test group by age having count(*)>=2; -- order by 排序 select * from test order by age; -- 默认asc 升序 select * from test order by age asc; --等同上 select * from test order by age desc; -- 降序