表結構
create table U
(
NAME CHAR(64) not null,
ID INTEGER not null PRIMARY KEY
)
tablespace CICI;
comment on table U
is '使用者表';
create table GROU
(
NAME CHAR(64) not null,
ID INTEGER not null PRIMARY KEY
)
tablespace CICI;
comment on table GROU
is '許可權組表';
CREATE TABLE U_GROU
(
G_ID INTEGER not null ,
U_ID INTEGER not null
)
tablespace CICI;
comment on table TABLE U_GROU
is '關係表';
alter table U_GROU
add foreign key (G_ID)
references GROU (ID);
alter table U_GROU
add foreign key (U_ID)
references U (ID);
資料
INSERT INTO U VALUES ('U1',1);
INSERT INTO U VALUES ('U1',2);
INSERT INTO GROU VALUES ('G1',1);
INSERT INTO GROU VALUES ('G1',2);
INSERT INTO u_GROU VALUES (1,1);
INSERT INTO u_GROU VALUES (1,2);
INSERT INTO u_GROU VALUES (2,2);
查詢目的 查詢使用者id 為1的使用者對應的許可權組
SELECT * FROM GROU WHERE EXISTS (
SELECT * FROM U_GROU WHERE GROU.ID = U_GROU.G_ID AND EXISTS (
SELECT * FROM U WHERE U.ID = U_GROU.U_ID AND U.ID = 1
)
);
查詢 name為U1的使用者對應的許可權組
SELECT * FROM GROU WHERE EXISTS (
SELECT * FROM U_GROU WHERE EXISTS (
SELECT * FROM U WHERE U.name = 'U1' and U.ID = U_GROU.U_ID
) AND GROU.ID = U_GROU.G_ID
);
查詢過程
---> SELECT * FROM U WHERE U.name = 'U1' and u.id = 1 有值,返回真,所以有資料
---> SELECT * FROM U WHERE U.name = 'U1' and u.id = 2 有值,返回真,所以有資料
===>U_GROU 表的資料被全部查出
SELECT * FROM GROU where GROU.ID = 1 有值,返回真,所以有資料
SELECT * FROM GROU where GROU.ID = 2 有值,返回真,所以有資料
===>GROU表的資料被全查出
SELECT * FROM GROU WHERE EXISTS (
SELECT * FROM U_GROU WHERE EXISTS (
SELECT * FROM U WHERE U.name = 'U1' and u.id = u_grou.u_id and rownum=1
) AND GROU.ID = U_GROU.G_ID
);
查詢過程 ??
exist實質
http://zlk.iteye.com/blog/903322