1、内连接--等值连接
自然连接,两个表相匹配的行才在结果集中出现
Select 内容 from 表1 inner join 表2 on 等值条件
Select * from student inner join grade on grade.stuid = student.stuid;
2、外连接
左连接:select 内容 from 表1 left outer join 表2 on 等值条件
右连接:select 内容 from 表1 right outer join 表2 on 等值条件
左连接按左表内容全部显示,右表数据无关联则显示null
右连接按右表内容全部显示,左表数据无关联则显示null
Select * from student right outer join grade on student.stuid = grade.stuid;
3、多表关联
Select 内容 from 表1,表2,表3 where 条件
Select * from student,course,grade where student.stuid = grade.stuid and course.couid = grade.couid and coursegrade > 80;
Select avg(coursegrade) from student,grade where student.stuid =grade.stuid and sex =’男’ and coursegrade is not null;
4.子查询--嵌套查询
当某一个查询条件实在另一个查询结果集里时,使用嵌套查询
Select * from grade where stuid = (select stuid from student where stname = ‘李四’);
Select * from grade where stuid in (select stuid from student where stname =’张三’or stname =’李四’);
Select * from grade where stuid = (select stuid from student where stname =’张三’) or stuid = (select stuid from student where stname =’李四’ );
Select stname from student where stuid in (select stuid from grade where coursegrade between 70 and 90);
Select stname,sex,stel from student where sno in (select sno from sc group by sno having count(cno)=(select count(cno) from course));
1、从数据表t1 中把那些id值在数据表t2 里有匹配的记录全删除掉
DELETE t1 FROM t1,t2 WHERE t1.id=t2.id 或
DELETE FROM t1 USING t1,t2 WHERE t1.id=t2.id
2、从数据表t1里在数据表t2里没有匹配的记录查找出来并删除掉
DELETE t1 FROM t1 LEFT JOIN T2 ON t1.id=t2.id WHERE t2.id IS NULL 或
DELETE FROM t1,USING t1 LEFT JOIN T2 ON t1.id=t2.id WHERE t2.id IS NULL
3、从两个表中找出相同记录的数据并把两个表中的数据都删除掉
DELETE t1,t2 from t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t1.id=25
注意此处的delete t1,t2 from 中的t1,t2不能是别名
如:delete t1,t2 from table_name as t1 left join table2_name as t2 on t1.id=t2.id where table_name.id=25 在数据里面执行是错误的(MYSQL 版本不小于5.0在5.0中是可以的)
delete table_name,table2_name from table_name as t1 left join table2_name as t2 on t1.id=t2.id where table_name.id=25 在数据里面执行是错误的(MYSQL 版本小于5.0在5.0中是可以的)
另外补充DELETE语句基本用法 :
1.删除表中某行 DELETE FROM 表名称 WHERE 列名称 = 值
2.删除所有行,在不删除表的情况下删除所有的行 DELETE FROM table_name / DELETE * FROM table_name