Problem Background:
How can the COUNT function value of the following SQL statement be larger than the number of T_1 rows and T_2 rows in the table? Is it an ORACLE database BUG?
SQL:
Select count (*) from t_1, t_2 where t_1.id = t_2.id and t_1.id = 1;
The T_1 and T_2 tables are structured as follows:
Create table t_1
(
Id number,
C1_1 varchar2 (63 ),
C2_1 varchar2 (63)
);
Create table t_2
(
Id number,
C1_2 varchar2 (63 ),
C2_2 varchar2 (63)
);
Solution:
1. The reason why application development engineers have doubts about this simple SQL statement is as follows:
A). There will basically be One-To-One and One-To-One relationships between Application System database tables faced by development engineers, thus forming a mindset. If the id field is used between T_1 and T_2 To form One-To-One and One-To-least associations, the COUNT value above is indeed no larger than the number of rows in the tables on the other side of the queue.
B) The Development Engineer did not have a fundamental understanding of SQL, such as the program logic of the SELECT statement.
2. Problem Analysis:
SQL> select * from t_1;
ID C1_1 C2_1
------------------------------
1 c1_1_r1 c2_1_r1
1 c1_1_r2 c2_1_r2
3 c1_1_r3 c2_1_r3
4 c1_1_r4 c2_1_r4
1 c1_1_r5 c2_1_r5
SQL> select * from t_2;
ID C1_2 C2_2
------------------------------
1 c1_2_r1 c2_2_r1
2 c1_2_r2 c2_2_r2
3 c1_2_r3 c2_2_r3
1 c1_2_r4 c2_2_r4
SQL> select count (*) from t_1, t_2 where t_1.id = t_2.id and t_1.id
COUNT (*)
----------
6
SQL> select * from t_1, t_2 where t_1.id = t_2.id and t_1.id = 1;
ID C1_1 C2_1 ID C1_2 C2_2
------------------------------------------------------------
1 c1_1_r1 c2_1_r1 1 c1_2_r4 c2_2_r4
1 c1_1_r1 c2_1_r1 1 c1_2_r1 c2_2_r1
1 c1_1_r2 c2_1_r2 1 c1_2_r4 c2_2_r4
1 c1_1_r2 c2_1_r2 1 c1_2_r1 c2_2_r1
1 c1_1_r5 c2_1_r5 1 c1_2_r4 c2_2_r4
1 c1_1_r5 c2_1_r5 1 c1_2_r1 c2_2_r1
Note: The last SQL statement compares all records in Table T_1 meeting the condition id = 1 with records in Table T_2 one by one. If the condition is met, a record is formed.
Author chhuma Column