这节将总结下在工作中经常遇到一些对于sql的理解不到位问题,比如说:
CREATE TABLE TEST ( DATE datetime, SEQ INT, RES CHAR(2) ) insert into TEST select ‘2010-8-7‘,1,‘A‘; insert into TEST select ‘2010-8-7‘,2,‘B‘ insert into TEST select ‘2010-8-8‘,1,‘A‘; insert into test select ‘2010-8-7‘,1,‘B‘;
SELECT * FROM TEST 后得到四条结果:
2010-08-07 00:00:00.000 1 A
2010-08-07 00:00:00.000 2 B
2010-08-08 00:00:00.000 1 A
2010-08-07 00:00:00.000 1 B
比较如下两条sql:
1:SELECT * FROM TEST A WHERE RES=(SELECT MAX(B.RES) FROM TEST B WHERE A.DATE=B.DATE AND A.SEQ=B.SEQ);
2:SELECT MAX(B.RES) FROM TEST B,TEST A WHERE A.DATE=B.DATE AND A.SEQ=B.SEQ;
sql 1: 这个会选择出满足 A.DATE=B.DATE AND A.SEQ=B.SEQ 条件下的所有的max(res),比方说2010-08-07,1有两条,但由于取max,因此只取出 2010-08-07,1,b那条。
SQL2:只会取出一个B
时间: 2024-10-10 20:47:39