[Sql]EXCEPT ºÍ INTERSECT¹Ø¼ü×Ö
[Sql]EXCEPT ºÍ INTERSECT¹Ø¼ü×Ö
http://www.cnblogs.com/treeyh/archive/2008/07/01/1232845.html
EXCEPT
´Ó EXCEPT ²Ù×÷Êý×ó±ßµÄ²éѯÖзµ»ØÓұߵIJéѯδ·µ»ØµÄËùÓзÇÖظ´Öµ¡£
INTERSECT
·µ»Ø INTERSECT ²Ù×÷Êý×óÓÒÁ½±ßµÄÁ½¸ö²éѯ¾ù·µ»ØµÄËùÓзÇÖظ´Öµ¡£
A. ʹÓà EXCEPT
ÔÚʾÀýÖÐʹÓà TableA ºÍ TableB ÖеÄÊý¾Ý¡£
TableA (col1 int)
TableB (col1 int)
NULL
NULL
NULL
1
NULL
3
1
4
2
4
2
2
3
4
4
ÒÔϲéѯ´Ó EXCEPT
²Ù×÷Êý×ó²àµÄ²éѯ·µ»ØÓÒ²à²éѯûÓÐÕÒµ½µÄËùÓзÇÖظ´Öµ¡£
SELECT * from TableA EXCEPT
SELECT * from TableB;
ÏÂÃæÊǽá¹û¼¯£º
Col1
-----------
2
(1 row(s) affected)
B. ʹÓà INTERSECT
ÔÚʾÀýÖÐʹÓà TableA ºÍ TableB ÖеÄÊý¾Ý¡£
TableA (col1 int)
TableB (col1 int)
NULL
2
NULL
2
NULL
2
1
4
2
4
2
2
3
4
4
ÒÔϲéѯ·µ»Ø INTERSECT
²Ù×÷Êý×óÓÒÁ½²àµÄÁ½¸ö²éѯ¾ù·µ»ØµÄËùÓзÇÖظ´Öµ¡£
SELECT * from TableA INTERSECT
SELECT * from TableB;
ÏÂÃæÊǽá¹û¼¯£º
Col1
-----------
2
4
(2 row(s) affected)
Ïà¹ØÎĵµ£º
ÉÏ΢ÈíÍøÕ¾ÏÂÔØsqlserver2005 jdbc driver °ü
1¡¢½«microsoft sql server 2005 jdbc driver\sqljdbc_1.2\chs\sqljdbc.jar°ü copyµ½·¢²¼ÏµÍ³ µÄ web-inf\libĿ¼ÖÐ
2¡¢½«microsoft sql server 2005 jdbc driver\sqljdbc_1.2\chs\auth\x86\sqljdbc_auth.dll Îļþcopyµ½ windows ......
1.¶Ô²éѯ½øÐÐÓÅ»¯£¬Ó¦¾¡Á¿±ÜÃâÈ«±íɨÃ裬Ê×ÏÈÓ¦¿¼ÂÇÔÚ where ¼° order by Éæ¼°µÄÁÐÉϽ¨Á¢Ë÷Òý¡£
2.Ó¦¾¡Á¿±ÜÃâÔÚ where ×Ó¾äÖжÔ×ֶνøÐÐ null ÖµÅжϣ¬·ñÔò½«µ¼ÖÂÒýÇæ
·ÅÆúʹÓÃË÷Òý¶ø½øÐÐÈ«±íɨÃ裬È磺
select id from t where num is null
¿ÉÒÔÔÚnumÉÏÉèÖÃ
ĬÈÏÖµ0£¬È·±£±íÖÐnumÁÐûÓÐnullÖµ£¬È»ºóÕâ
Ñù²éѯ£º
sel ......
¾³£»á¿´¼ûÔÚSQL³ÌÐòµÄ¿ªÍ·ÓÐÕâÑùÒ»¾ä»°
if OBJECT_ID('tb') is not null
drop table tb
º¯ÊýÓï·¨ÊÇÕâÑù£º
int OBJECT_ID('objectname');
×÷ÓÃÊÇ¿´¶ÔÏóobjectnameÊÇ·ñ´æÔÚ¡£
ÆäÖвÎÊýobjectname±íʾҪʹÓõĶÔÏó£¬ÊÇchar»òÕßncharÀàÐÍ¡£
·µ»ØÖµÀàÐÍΪint£¬Èç¹û¶ÔÏó´æÔÚ£¬Ôò·µ»Ø´Ë¶ÔÏóÔÚϵͳÖеı ......
ÔÚsqlÓï¾äÖÐÌí¼Ó±äÁ¿¡£
declare @local_variable data_type
ÉùÃ÷ʱÐèÒªÖ¸¶¨±äÁ¿µÄÀàÐÍ£¬
¿ÉÒÔʹÓÃsetºÍselect¶Ô±äÁ¿½øÐи³Öµ£¬
ÔÚsqlÓï¾äÖоͿÉÒÔʹÓÃ@local_variableÀ´µ÷ÓñäÁ¿
ÉùÃ÷ÖпÉÒÔÌṩֵ£¬·ñÔòÉùÃ÷Ö®ºóËùÓбäÁ¿½«³õʼ»¯ÎªNULL¡£
ÀýÈ磺declare @id int
&nb ......
ÔÚSQLÓïÑÔÖУ¬Ö»ÌṩÁËÒ»¸ö¶¯´ÊSELECTÓÃÀ´½øÐÐÊý¾Ý²éѯ²Ù×÷£¬µ«Õâ¸ö¶¯´ÊµÄ²ÎÊýÊ®·Ö¸´ÔÓ£¬ÇÒÄÜǶÌ×ʹÓã¬ÆäͨÓøñʽÈçÏ£º
SELECT [All|Distinct]<Ä¿±êÁбí´ïʽ>[£¬<Ä¿±êÁбí´ïʽ>]...
from <±íÃû»òÊÓͼÃû>[£¬<±íÃû»òÊÓͼÃû>]...
[WHERE<Ìõ¼þ±í´ïʽ>]
[GROUP BY<ÁÐÃû1>[HAVING<Ì ......