首页 > 数据库技术 > 详细

oracle 关系除法

时间:2016-02-16 18:31:56      阅读:372      评论:0      收藏:0      [点我收藏+]

2016-02-16

关系除法 R÷S

关系模式 R(X,Y) S(Y,Z)

含义:在R中查询与S中所有元组有关系的元组

一、创建基础表R和S

CREATE TABLE R (X VARCHAR2(10),Y VARCHAR2(10));
CREATE TABLE S (Y VARCHAR2(10),Z VARCHAR2(10));

INSERT ALL
INTO R VALUES (X1,Y1)
INTO R VALUES (X2,Y2)
INTO R VALUES (X2,Y3)
INTO R VALUES (X2,Y1)
SELECT 1 FROM DUAL;

INSERT ALL
INTO S VALUES (Y1,Z1)
INTO S VALUES (Y2,Z3)
SELECT 1 FROM DUAL;FROM R;

二、分解 

--R
SELECT * FROM R;

技术分享

--S
SELECT * FROM S;

技术分享

--T
SELECT Y FROM S;
CREATE TABLE T AS SELECT Y FROM S;
SELECT * FROM T;

技术分享

--W
SELECT R.X, R.Y FROM (SELECT Y FROM S) T LEFT JOIN R ON T.Y = R.Y;
CREATE TABLE W AS SELECT R.X, R.Y FROM (SELECT Y FROM S) T LEFT JOIN R ON T.Y = R.Y;
SELECT * FROM W;

技术分享

--N
SELECT COUNT(*) Y_NUM FROM T;
CREATE TABLE N AS SELECT COUNT(*) Y_NUM FROM T;
SELECT * FROM N;

技术分享

--M
SELECT X, COUNT(*) Y_NUM FROM W GROUP BY X;
CREATE TABLE M AS SELECT X, COUNT(*) Y_NUM FROM W GROUP BY X;
SELECT * FROM M;

技术分享

--R÷S
SELECT M.X FROM M RIGHT JOIN N ON M.Y_NUM = N.Y_NUM;

技术分享

三、综合

SELECT M.X
  FROM (SELECT X, COUNT(*) Y_NUM
          FROM (SELECT R.X, R.Y
                  FROM (SELECT Y FROM S) T
                  LEFT JOIN R
                    ON T.Y = R.Y) W
         GROUP BY X) M
 RIGHT JOIN (SELECT COUNT(*) Y_NUM FROM (SELECT Y FROM S) T) N
    ON M.Y_NUM = N.Y_NUM;

技术分享

 

oracle 关系除法

原文:http://www.cnblogs.com/cenliang/p/5193463.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!