比如现在有两张表:用户表:
userid --用户ID
username --用户名
departmentId --部门(引用部门表)部门表
departmentId --部门ID
departmentName --部门名称
我现在要查询用户表,并且把用户表里面的departmentId直接级联成部门表中的名称,这个要怎么查询呀?求高手帮助~
userid --用户ID
username --用户名
departmentId --部门(引用部门表)部门表
departmentId --部门ID
departmentName --部门名称
我现在要查询用户表,并且把用户表里面的departmentId直接级联成部门表中的名称,这个要怎么查询呀?求高手帮助~
select a.userid, a.username, b.departmentName
from user_table a,dept_table b where a.departmentId = b.departmentId ;
--使用等值连接
SQL> select e.empno,e.ename,d.dname
2 from emp e,dept d
3 where e.deptno=d.deptno
4 /
EMPNO ENAME DNAME
----- ---------- --------------
7782 CLARK ACCOUNTING
7839 KING ACCOUNTING
7934 MILLER ACCOUNTING
7369 SMITH RESEARCH
7876 ADAMS RESEARCH
7902 FORD RESEARCH
7788 SCOTT RESEARCH
7566 JONES RESEARCH
7499 ALLEN SALES
7698 BLAKE SALES
7654 MARTIN SALES
7900 JAMES SALES
7844 TURNER SALES
7521 WARD SALES
14 rows selected
SQL>
如果用户表里面同时引用了多个部门要该怎么办呀?比如这样的结构:用户表:
userid --用户ID
username --用户名
regDepartmentId --注册部门
orderDepartmentId --所属部门
部门表
departmentId --部门ID
departmentName --部门名称
select a.userid,a.username,a.regDepartmentId,a.orderDepartmentId,b.departmentName
from user_table a,dept_table b,dept_table c
where a.regDepartmentId = b.departmentId
and a.orderDepartmentId = c.departmentId
,b.departmentName,c.departmentName
from user_table a,dept_table b,dept_table c
where a.regDepartmentId = b.departmentId
and a.orderDepartmentId = c.departmentId