由于我对这篇文章的评论受到批评,我准备了一个例子来说明我对这个主题的看法。
以下 Oracle 脚本说明了我认为使用该NATURAL JOIN
构造所固有的危险。我承认这是一个人为的例子,但为了防御性发展,我相信我的立场是正确的。
DROP TABLE TABLE1;
DROP TABLE TABLE2;
CREATE TABLE TABLE1 (
FIELD1 VARCHAR2(10),
FIELD2 VARCHAR2(10),
DESCR_T1 VARCHAR2(20)
);
CREATE TABLE TABLE2 (
FIELD1 VARCHAR2(10),
FIELD2 VARCHAR2(10),
DESCR_T2 VARCHAR2(20)
);
INSERT INTO TABLE1 VALUES('AAA','AAA', 'AAA_AAA_T1' );
INSERT INTO TABLE1 VALUES('BBB','BBB', 'BBB_BBB_T1' );
INSERT INTO TABLE1 VALUES('CCC','T1_CCC', 'CCC_T1_CCC_T1');
INSERT INTO TABLE1 VALUES('DDD','T1_DDD', 'DDD_T1_DDD_T1');
INSERT INTO TABLE1 VALUES('EEE',NULL , 'EEE_NULL_T1' );
INSERT INTO TABLE2 VALUES('AAA','AAA', 'AAA_AAA_T2' );
INSERT INTO TABLE2 VALUES('BBB','BBB', 'BBB_BBB_T2' );
INSERT INTO TABLE2 VALUES('CCC','T2_CCC', 'CCC_T1_CCC_T2');
INSERT INTO TABLE2 VALUES('DDD','T2_DDD', 'DDD_T1_DDD_T2');
INSERT INTO TABLE2 VALUES('EEE',NULL , 'EEE_NULL_T2' );
COMMIT;
-- try the following queries and review the results
SELECT
FIELD1, DESCR_T1, DESCR_T2
FROM
TABLE1 NATURAL JOIN TABLE2;
SELECT
*
FROM
TABLE1 NATURAL JOIN TABLE2;
SELECT
TABLE1.FIELD1, TABLE1.DESCR_T1, TABLE2.DESCR_T2
FROM
TABLE1 JOIN
TABLE2 ON
TABLE2.FIELD1 = TABLE1.FIELD1 AND
TABLE2.FIELD2 = TABLE1.FIELD2;
SELECT * FROM
TABLE1 NATURAL JOIN TABLE2;
-- Issue the following statement then retry the previous 3 statements.
-- The 'NJs' silently change behaviour and produce radically different results
-- whereas the third requires hands-on attention. I believe this third behaviour
-- is desirable. (You could equally drop the column TABLE2.FIELD2 as dportas
-- has suggested
-- ALTER TABLE TABLE2 RENAME COLUMN FIELD2 TO T2_FIELD2;