SQL SubqueryµÄÓ÷¨
ÎÒÃÇ¿ÉÒÔÔÚÒ»¸ö SQL Óï¾äÖзÅÈëÁíÒ»¸ö SQL Óï¾ä¡£µ±ÎÒÃÇÔÚ WHERE ×Ó¾ä»ò WHERE ×Ó¾ä»ò HAVING ×Ó¾äÖвåÈëÁíÒ»¸ö SQL Óï¾äʱ£¬ÎÒÃǾÍÓÐÒ»¸ö subquery µÄ¼Ü¹¹¡£ Subquery µÄ×÷ÓÃÊÇʲôÄØ£¿µÚÒ»£¬Ëü¿ÉÒÔ±»ÓÃÀ´Á¬½Ó±í¸ñ¡£ÁíÍ⣬ÓеÄʱºò subquery ÊÇΨһÄܹ»Á¬½ÓÁ½¸ö±í¸ñµÄ·½Ê½¡£
Subquery µÄÓï·¨ÈçÏ£º
SELECT "À¸Î»1"
from "±í¸ñ"
WHERE "À¸Î»2" [±È½ÏÔËËãËØ]
(SELECT "À¸Î»1"
from "±í¸ñ"
WHERE [Ìõ¼þ])
[±È½ÏÔËËãËØ] ¿ÉÒÔÊÇÏàµÈµÄÔËËãËØ£¬ÀýÈç =, >, <, >=, <=. ÕâÒ²¿ÉÒÔÊÇÒ»¸ö¶ÔÎÄ×ÖµÄÔËËãËØ£¬ÀýÈç "LIKE."
ÎÒÃǾÍÓøոÕÔÚ²ûÊö SQL Á¬½ÓʱÓùýµÄÀý×Ó£º
Store_Information ±í¸ñ
store_name
Sales
Date
Los Angeles
$1500
Jan-05-1999
San Diego
$250
Jan-07-1999
Los Angeles
$300
Jan-08-1999
Boston
$700
Jan-08-1999
Geography ±í¸ñ
region_name
store_name
East
Boston
East
New York
West
Los Angeles
West
San Diego
ÎÒÃÇÒªÔËÓà subquery À´ÕÒ³öËùÓÐÔÚÎ÷²¿µÄµêµÄÓªÒµ¶î¡£ÎÒÃÇ¿ÉÒÔÓÃÏÂÃæµÄ SQL À´´ïµ½ÎÒÃǵÄÄ¿µÄ£º
SELECT SUM(Sales) from Store_Information
WHERE Store_name IN
(SELECT store_name from Geography
WHERE region_name = 'West')
½á¹û:
SUM(Sales)
2050
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃDz¢Ã»ÓÐÖ±½Ó½«Á½¸ö±í¸ñÁ¬½ÓÆðÀ´£¬È»ºóÓÉ´ËÖ±½ÓËã³öÿһ¼äÎ÷ÇøµêÃæµÄÓªÒµ¶î¡£ÎÒÃÇ×öµÄÊÇÏÈÕÒ³öÄÄЩµêÊÇÔÚÎ÷ÇøµÄ£¬È»ºóÔÙËã³öÕâЩµêµÄÓªÒµ¶î×ܹ²ÊǶàÉÙ¡£
Ïà¹ØÎĵµ£º
SELECT Ö¸ÁîÈÃÎÒÃÇÄܹ»¶ÁÈ¡±í¸ñÖÐÒ»¸ö»òÊý¸öÀ¸Î»µÄËùÓÐ×ÊÁÏ¡£ Õ⽫°ÑËùÓеÄ×ÊÁ϶¼×¥³ö£¬ÎÞÂÛ×ÊÁÏÖµÓÐÎÞÖظ´¡£ÔÚ×ÊÁÏ´¦ÀíÖУ¬ÎÒÃǻᾳ£Åöµ½ÐèÒªÕÒ³ö±í¸ñÄڵIJ»Í¬ ×ÊÁÏÖµµÄÇé¿ö¡£»»¾ä»°Ëµ£¬ÎÒÃÇÐèÒªÖªµÀÕâ¸ö±í¸ñ/À¸Î»ÄÚÓÐÄÄЩ²»Í¬µÄÖµ£¬¶øÿ¸öÖµ³öÏֵĴÎÊý²¢²»ÖØÒª¡£ÕâÒªÈçºÎ´ï³ÉÄØ£¿ÔÚ SQL ÖУ¬ÕâÊǺÜÈÝÒ××öµ½µÄ¡£ÎÒÃÇÖ»ÒªÔ ......
ÔÚÉÏÒ»Ò³ÖУ¬ÎÒÃÇ¿´µ½ WHERE Ö¸Áî¿ÉÒÔ±»ÓÃÀ´Óɱí¸ñÖÐ ÓÐÌõ¼þµØÑ¡È¡×ÊÁÏ¡£ Õâ¸öÌõ¼þ¿ÉÄÜÊǼòµ¥µÄ (ÏñÉÏÒ»Ò³µÄÀý×Ó)£¬Ò²¿ÉÄÜÊǸ´Ôӵġ£¸´ÔÓÌõ¼þÊÇÓɶþ»ò¶à¸ö¼òµ¥Ìõ¼þ͸¹ý AND »òÊÇ OR µÄÁ¬½Ó¶ø³É¡£Ò»¸ö SQL Óï¾äÖпÉÒÔÓÐÎÞÏÞ¶à¸ö¼òµ¥Ìõ¼þµÄ´æÔÚ¡£
¸´ÔÓÌõ¼þµÄÓï·¨ÈçÏ£º
SELECT "À¸Î»Ãû"
from "±í¸ñÃû"
WHERE "¼òµ¥Ìõ¼ ......
IN Õâ¸öÖ¸Áî¿ÉÒÔÈÃÎÒÃÇÒÀÕÕÒ»»òÊý¸ö²»Á¬Ðø (discrete) µÄÖµµÄÏÞÖÆÖ®ÄÚ×¥³öÊý¾Ý¿âÖеÄÖµ£¬¶ø BETWEEN ÔòÊÇÈÃÎÒÃÇ¿ÉÒÔÔËÓÃÒ»¸ö·¶Î§ (range) ÄÚ×¥³öÊý¾Ý¿âÖеÄÖµ¡£BETWEENÕâ¸ö×Ó¾äµÄÓï·¨ÈçÏ£º
SELECT "À¸Î»Ãû"
from " ±í¸ñÃû"
WHERE "À¸Î»Ãû" BETWEEN 'ÖµÒ»' AND 'Öµ¶þ'
Õ⽫ѡ³öÀ¸Î»Öµ°üº¬ÔÚÖµÒ»¼°Öµ¶þÖ®¼äµÄÿһ±Ê× ......
µ½Ä¿Ç°ÎªÖ¹£¬ÎÒÃÇÒÑѧµ½ÈçºÎ½åÓÉ SELECT ¼° WHEREÕâÁ½¸öÖ¸Á×ÊÁÏÓɱí¸ñÖÐ×¥³ö¡£²»¹ýÎÒÃÇÉÐδÌáµ½ÕâЩ×ÊÁÏÒªÈçºÎÅÅÁС£ÕâÆäʵÊÇÒ»¸öºÜÖØÒªµÄÎÊÌâ¡£ÊÂʵÉÏ£¬ÎÒÃǾ³£ÐèÒªÄܹ»½«×¥³öµÄ×ÊÁÏ×öÒ»¸öÓÐϵͳµÄÏÔʾ¡£Õâ¿ÉÄÜÊÇÓÉСÍù´ó (ascending) »òÊÇÓÉ´óÍùС(descending)¡£ÔÚÕâÖÖÇé¿öÏ£¬ÎÒÃǾͿÉÒÔÔËÓà ORDER BYÕâ¸öÖ¸ÁîÀ´´ïµ½ ......
ÔÚÉÏÒ»Ò³ÓÐÌáµ½£¬COUNT ÊǺ¯ÊýÖ®Ò»¡£ÓÉÓÚËüµÄʹÓù㷺£¬ÎÒÃÇÔÚÕâÀïÌرðÌá³öÀ´ÌÖÂÛ¡£»ù±¾ÉÏ£¬COUNT ÈÃÎÒÃÇÄܹ»Êý³öÔÚ±í¸ñÖÐÓжàÉÙ±Ê×ÊÁϱ»Ñ¡³öÀ´¡£ËüµÄÓï·¨ÊÇ£º
SELECT COUNT("À¸Î»Ãû")
from "±í¸ñÃû"
¾ÙÀýÀ´Ëµ£¬ÈôÎÒÃÇÒªÕÒ³öÎÒÃǵÄʾ·¶±í¸ñÖÐÓм¸±Ê store_name À¸²»ÊÇ¿Õ°×µÄ×ÊÁÏʱ£¬
Store_Information ±í¸ñ
store ......