Posted on 2008-08-12 15:54
Prayer 閱讀(237)
評論(0) 編輯 收藏 引用 所屬分類:
數(shù)據(jù)庫,SQL
**********************************************************************************
聯(lián)合查詢
**********************************************************************************
查詢表中的各個字段的值
select Sno,Sname,Ssex,Sdept from Student;
多表查詢(2個表,publishtable和publishtable,給表起了別名)
select u.userid,u.age,u.username,p.publishname from usertable u,publishtable p where u.userid = p.publishid;
多表查詢(3個表employees,departments和locations表,給表起別名)
(從多表中查詢出所有姓smith的雇員的名字,所在部門以及部門所在的城市)
select e.first_name,e.last_name,d.department_name,l.city from employees e,departments d,locations l where e.department_id = d.department_id and d.location_id = l.location_id and e.last_name = 'smith';
***********************************************************************************
聯(lián)合查詢
***********************************************************************************
等值連接
/*將books表和表bookstype中的信息聯(lián)合查詢,條件是聯(lián)系鍵相等*/
select * from books,bookstype where bookstype.typeid = books.typeid
內(nèi)連接
/*將books表和表bookstype中的信息聯(lián)合查詢,條件是聯(lián)系鍵相等,和等值連接等價*/
select * from books inner join bookstype on books.typeid = bookstype.typeid
左外連接
/*將books表和表bookstype中的信息聯(lián)合查詢,包括在books表中沒有和bookstype表關(guān)聯(lián)的信息*/
select * from books left outer join bookstype on bookstype.typeid = books.typeid
右外連接
/*將bookstype表和books表中的信息聯(lián)合查詢,包括在bookstype表中沒有和books表關(guān)聯(lián)的信息*/
select * from books right outer join bookstype on bookstype.typeid = books.typeid
全連接
/*將bookstype表和books表中的信息聯(lián)合查詢,包括在books表中沒有和bookstype表關(guān)聯(lián)的信息以及在bookstype表中沒有和books表關(guān)聯(lián)的信息*/
select * from books full outer join bookstype on bookstype.typeid = books.typeid
***********************************************************************************
聯(lián)合查詢
***********************************************************************************
多表查詢應(yīng)該注意的幾點:
多表查詢和單表查詢的不同在于多表查詢在查詢某個字段的時候應(yīng)該帶上表名
格式是:表名.字段名,表名.字段名
select bbs.id,bbs.name,bbs.dep,bbsr.id,bbsr.name
from bbs,bbsr
where bbs.id=bbsr.id;
一般的在多表查詢中的表名取的麻煩用別名來代替
如下:
select b.id,b.name,b.dep,c.id,c.name
from bbs as b ,bbsr as c // from bbs b,bbsr c***注意取別名也可以用空格或則用as.
where b.id=c.id;