如何进行按列分区的交叉连接?

时间:2015-02-09 11:53:20

标签: sql oracle join

我想在两列之间有一个笛卡尔积。以下是示例数据:

CREATE TABLE CART (
MYSK NUMBER, 
MYPROD VARCHAR(50 CHAR),
CUST VARCHAR(50 CHAR)
)
;
INSERT INTO CART (MYSK, MYPROD, CUST)
VALUES('1', 'A', 'Jim');
COMMIT;
INSERT INTO CART (MYSK, MYPROD, CUST)
VALUES('2', 'B', 'Jim');
COMMIT;
INSERT INTO CART (MYSK, MYPROD, CUST)
VALUES('4', 'A', 'Jack');
COMMIT;
INSERT INTO CART (MYSK, MYPROD, CUST)
VALUES('5', 'B', 'Jack');
COMMIT;
INSERT INTO CART (MYSK, MYPROD, CUST)
VALUES('7', 'C', 'Jack');
COMMIT;

如何在列MYSK ja MYPROD之间进行交叉连接,以便交叉连接仅适用于CUST列,而不适用于所有行?这会产生错误的结果:

SELECT AA.MYSK, BB.MYPROD, BB.CUST
FROM CART AA 
CROSS JOIN CART BB
;

正确的结果集如下:

+------+--------+------+
| MYSK | MYPROD | CUST |
+------+--------+------+
|    1 | A      | Jim  |
|    2 | A      | Jim  |
|    1 | B      | Jim  |
|    2 | B      | Jim  |
|    4 | A      | Jack |
|    5 | A      | Jack |
|    7 | A      | Jack |
|    4 | B      | Jack |
|    5 | B      | Jack |
|    7 | B      | Jack |
|    4 | C      | Jack |
|    5 | C      | Jack |
|    7 | C      | Jack |
+------+--------+------+

1 个答案:

答案 0 :(得分:2)

我想你只想要join。试试这个:

SELECT AA.MYSK, BB.MYPROD, BB.CUST
FROM CART AA JOIN
     CART BB
     ON AA.CUST = BB.CUST;