SQLÓïÑÔ»ù´¡£¨4£©
UNION½«Á½¸ö»òÁ½¸öÒÔÉϵIJéѯ½á¹ûºÏ²¢ÎªÒ»¸ö½á¹û¼¯£¬ËüÓëʹÓÃÁ¬½Ó²éѯºÏ²¢Á½¸ö±íµÄÁÐÊDz»Í¬µÄ£¬Ê¹
ÓÃUNIONºÏ²¢²éѯ±ØÐë×ñÊØ£º1ÁеÄÊýÄ¿ºÍ˳Ðò±ØÐëÒ»Ö£»2Êý¾ÝµÄÀàÐͱØÐë¼æÈÝ¡£
select Óï¾ä
UNION [all]
select Óï¾ä
¿ÉÒÔ¿´µ½£¬Ö»Òª¶ÔÓ¦×ֶεÄÀàÐÍÏàͬ¾Í¿ÉÒÔÍê³ÉºÏ²¢²Ù×÷£¬µ«ÊÇΪÁËÓÐÒâÒ壬Á½¸ö²éѯµÄ½á¹ûÓ¦¸ÃΪÏàͬ
µÄº¬Ò壬·ñÔòûÓÐÒâÒå¡£
½á¹û×Ö¶ÎÃû³ÆºÍunion֮ǰµÄ×Ö¶ÎÃû³ÆÏàͬ£¬Ä¬ÈÏÇé¿öÏÂɾ³ý½á¹û¼¯ÖеÄÖظ´¼Ç¼£¬Èç¹ûÏ£Íû±£ÁôËùÓмÇ
¼£¬Ôò±ØÐëʹÓÃall¹Ø¼ü×Ö¡£
ʹÓÃunionʱµ¥¶ÀµÄselectÓï¾ä²»ÄÜ°üº¬×Ô¼ºµÄorder by»òcompute×Ӿ䣬ֻÄÜÔÚ×îºóʹÓÃorder byºÍ
computeÓï¾ä£¬¶Ô×îÖÕ½á¹û¼¯½øÐÐ×÷Óá£
ÈôÐèÒª¶Ô²éѯ½á¹û½øÐзÖ×éÒÔ¼°ÔÚ·Ö×éºó¶Ô½á¹ûʹÓÃhaving×Ó¾ä½øÐйýÂË£¬Ôò±ØÐëÔÚµ¥¶ÀµÄselectÓï¾äÖÐ
Ö¸¶¨group byºÍhaving×Ӿ䡣
²éѯ¼ÆËã»úϵµÄѧÉú»òÕßÄêÁä²»´óÓÚ19ËêµÄѧÉú£¬²¢°´ÄêÁäµ¹ÅÅÐò
select * from student where sdept="¼ÆËã»ú"
union
select * from student where sage<=19
order by sage desc
Á¬½Ó²éѯ
¸ù¾ÝÊý¾Ý±íµÄÂß¼¹Øϵ´ÓÁ½¸ö»ò¶à¸öÊý¾Ý±íÖмìË÷Êý¾Ý
¶¨ÒåÊý¾Ý±íÖ®¼äµÄ¹ØÁª·½Ê½£º1Ö¸¶¨ÓÃÓÚÁª½áµÄ×ֶΣ¬µäÐ͵ÄÁª½áÌõ¼þÊÇÔÚÒ»¸öÊý¾Ý±íÖÐÖ¸¶¨Íâ¼ü£¬Í¬ÊÂ
ÔÚÁíÒ»¸öÊý¾Ý±íÖÐÖ¸¶¨ÓëÆä¹ØÁªµÄÖ÷¼ü¡£2ÔÚselectÓï¾äÖÐÖ¸¶¨±È½Ï¸÷×Ö¶ÎֵʱҪʹÓõÄÂß¼ÔËËã·û¡£
Áª½áµÄÀàÐÍ£ºÄÚÁª½á£»ÍâÁª½á£¨×óÏòÍâÁ¬½Ó£¬ÓÒÏòÍâÁ¬½Ó£¬ÍêÕûÍâÁ¬½Ó£©£»½»²æÁ¬½Ó
ÄÚÁª½á¸ñʽ£ºÊý¾Ý±í1 inner join Êý¾Ý±í2 on Áª½á±í´ïʽ
Ö¸¶¨·µ»ØÁ½¸ö±íÖÐËùÓÐÆ¥ÅäµÄÐС£innerÊÇȱʡµÄÁ¬½Ó·½Ê½
ÍâÁ¬½Ó£ºÊý¾Ý±í1 left (outer) join Êý¾Ý±í2 on Áª½á±í´ïʽ
×óÁª½áÊý¾Ý±í1µÄËùÓмǼ¶¼·µ»Ø£¬ÓÒ±ß×Ö¶ÎûÓÐÆ¥ÅäʱΪ¿ÕÖµ¡£
Êý¾Ý±í1 right (outer) join Êý¾Ý±í2 on Áª½á±í´ïʽ
ÓÒÁª½áÊý¾Ý±í2µÄËùÓмǼ¶¼·µ»Ø£¬×ó±ß×Ö¶ÎûÓÐÆ¥ÅäʱΪ¿ÕÖµ¡£
ÍêÕûÁª½á£ºÊý¾Ý±í1 full join Êý¾Ý±í2 on Áª½á±í´ïʽ
½á¹û¼¯°üÀ¨ËùÓмǼ£¬Ã»ÓÐÆ¥Åä¼Ç¼ʱÔò½«ÁíÒ»Êý¾Ý±íÑ¡ÔñÁбí×Ö¶ÎÖÿա£
½»²æÁª½á£ºÊý¾Ý±í1 cross join Êý¾Ý±í2 £¨Ã»ÓÐwhere×Ó¾äµÄÇé¿öÏ·µ»ØµÑ¿¨¶û³Ë»ý£©
ǶÌײéѯ£ºÍâ²ã²éѯÊÇÖ÷²éѯ£¬ÄÚ²ã²éѯÊÇ×Ó²éѯ¡£SQLÔÊÐí¶à²ãǶÌ×£¬order by ×Ó¾äÖ»ÄܶÔ×îÖÕ²éѯ½á
¹û½øÐÐÅÅÐò¡£
±È½Ï³£ÓõÄ×Ó²éѯ£ºwhere ±í´ïʽ[not] in (×Ó²éѯ)
&
Ïà¹ØÎĵµ£º
SQL ServerÔÚ°²×°µ½·þÎñÆ÷ÉϺó£¬ÓÉÓÚ³öÓÚ·þÎñÆ÷°²È«µÄÐèÒª£¬ËùÒÔÐèÒªÆÁ±ÎµôËùÓв»Ê¹ÓõĶ˿ڣ¬Ö»¿ª·Å±ØÐëʹÓõĶ˿ڡ£ÏÂÃæ¾ÍÀ´½éÉÜÏÂSQL Server 2008ÖÐʹÓõĶ˿ÚÓÐÄÄЩ£º
Ê×ÏÈ£¬×î³£ÓÃ×î³£¼ûµÄ¾ÍÊÇ1433¶Ë¿Ú¡£Õâ¸öÊÇÊý¾Ý¿âÒýÇæµÄ¶Ë¿Ú£¬Èç¹ûÎÒÃÇÒªÔ¶³ÌÁ¬½ÓÊý¾Ý¿âÒýÇ棬ÄÇô¾ÍÐèÒª´ò¿ª¸Ã¶Ë¿Ú¡£Õâ¸ö¶Ë¿ÚÊÇ¿ÉÒÔÐ޸ĵģ¬ÔÚ&ldqu ......
group by
ÔÚselect Óï¾äÖпÉÒÔʹÓÃgroup by ×Ӿ佫Ðл®·Ö³É½ÏСµÄ×飬Ȼºó£¬Ê¹ÓþÛ×麯Êý·µ»Øÿһ¸ö×éµÄ»ã×ÜÐÅÏ¢£¬ÁíÍ⣬¿ÉÒÔʹÓÃhaving×Ó¾äÏÞÖÆ·µ»ØµÄ½á¹û¼¯¡£group by ×Ó¾ä¿ÉÒÔ½«²éѯ½á¹û·Ö×飬²¢·µ»ØÐеĻã×ÜÐÅÏ¢Oracle °´ÕÕgroup by ......
²éѯÓï¾ä
Óï·¨¸ñʽ£º
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_
[SQL_CACHE | SQL_ ......
¶ÔÏóÃüÃûµÄÔ¼¶¨£ºÊý¾Ý¿âÃû.ËùÓÐÕßÃû.¶ÔÏóÃû
Ç°Á½Õß¿ÉÊ¡ÂÔ£¬Ä¬ÈÏÖµÊý¾Ý¿âÊǵ±Ç°Êý¾Ý¿â£¬ËùÓÐÕßÊÇdbo
±ðÃû£ºÊý¾Ý¿âÃû³Æ as Êý¾Ý¿â±íÃû Ö÷ÒªÊÇÔö¼ÓselectÓï¾äµÄ¿É¶ÁÐÔ£¬Èç¹ûÒѾΪÊý¾Ý±íÖƶ¨Á˱ðÃû£¬Ôò
ÔÚÏàÓ¦µÄSQLÓï¾äÖУ¬¶Ô¸ÃÊý¾Ý±íµÄËùÓÐÏÔʾÒýÓö¼ÒªÊ¹ÓñðÃû£¬¶ø²»ÄÜʹÓÃÊý¾Ý±íÃû¡£
selectÓï¾äÊÇÊý¾Ý¼ìË÷ÖÐ×îƵ·±µÄ»î¶ ......
GROUP BY×Ó¾ä
Ö¸¶¨²éѯ½á¹ûµÄ·Ö×éÌõ¼þ
Óï·¨£ºGROUP BY [ALL] group_by_expression_r_r [,n]
[WITH{CUBE|ROLLUP}]
group_by_expression_r_rÖ¸Ã÷·Ö×éÌõ¼þ£¬Í¨³£ÊÇÒ»¸öÁÐÃû£¬µ«²»ÄÜÊÇÁеıðÃû¡£
ALL·µ»ØËùÓвéѯ½á¹ûµÄ×éºÏ¡£Èç¹ûûÓÐÂú×ãwhere×Ó¾äµÄÊý¾ÝÔòÓÉNULLÖµ¹¹³ÉÊý¾Ý¡£ALLµÄÑ¡Ïî²»Ä ......