交叉连接,内连接,子查询,外左连接,右连接,联合查询

Posted 111wdh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了交叉连接,内连接,子查询,外左连接,右连接,联合查询相关的知识,希望对你有一定的参考价值。

/*交叉连接*/
select*from emp join dept ;  没有on条件,出现多对多无意义连接
/*内连接*/两表有意义连接
写法1.SELECT * FROM emp JOIN dept ON emp.did=dept.did;
写法2.SELECT * FROM emp,dept WHERE emp.did=dept.did;

多表连接1.select*from 表1 join 表2 on  条件 join 表3 on 条件

多表连接2.

select sname,degree FROM 表1,表2,表3,表4 where(teacher.tno=course.tno AND course.cno=score.cno AND score.sno=student.sno)
AND tname=‘张旭‘

2.select * from 表1 ,表2 where 
/*查询小红所在部门名称*/
SELECT dname FROM emp JOIN dept ON emp.did=dept.did WHERE ename=‘小红‘;
SELECT dname FROM emp,dept WHERE emp.did=dept.did AND ename=‘小红‘;
/*查询测试部的员工姓名*/
SELECT ename FROM emp JOIN dept ON emp.did=dept.did WHERE dname=‘测试部‘;
/*工资最高员工所在部门名称*/
SELECT dname FROM emp JOIN dept ON emp.did=dept.did ORDER BY money DESC LIMIT 0,1;

/*子查询*/
SELECT did FROM emp WHERE ename=‘小红‘;
SELECT dname FROM dept WHERE did=(SELECT did FROM emp WHERE ename=‘小兰‘);
/*查询测试部的员工姓名*/
SELECT ename FROM emp WHERE did=(SELECT did FROM dept WHERE dname=‘测试部‘);
/*工资最高员工所在部门名称*/
SELECT dname FROM dept WHERE did=(SELECT did FROM emp ORDER BY money DESC LIMIT 0,1)

/*多个查询结果时需要用in*/
SELECT dname FROM dept WHERE did IN( SELECT did FROM emp WHERE money=2000)

 

-- 左外连接
SELECT * FROM dept LEFT JOIN emp ON emp.did=dept.did
-- 右连接
SELECT * FROM emp RIGHT JOIN dept ON emp.did=dept.did
-- 联合查询
SELECT eid,ename FROM emp
UNION
SELECT did,dname FROM dept

以上是关于交叉连接,内连接,子查询,外左连接,右连接,联合查询的主要内容,如果未能解决你的问题,请参考以下文章

mysql连接查询,子查询,联合查询

多表查询

MYSQL-多表查询

MySQL数据库多表查询

MySQL数据库多表查询

mysql数据库的多表查询,子查询,联合查询