SQL JOIN
SQL JOIN
SQL join ÓÃÓÚ¸ù¾ÝÁ½¸ö»ò¶à¸ö±íÖеÄÁÐÖ®¼äµÄ¹Øϵ£¬´ÓÕâЩ±íÖвéѯÊý¾Ý¡£
Join ºÍ Key
ÓÐʱΪÁ˵õ½ÍêÕûµÄ½á¹û£¬ÎÒÃÇÐèÒª´ÓÁ½¸ö»ò¸ü¶àµÄ±íÖлñÈ¡½á¹û¡£ÎÒÃǾÍÐèÒªÖ´ÐÐ join¡£
Êý¾Ý¿âÖеıí¿Éͨ¹ý¼ü½«±Ë´ËÁªÏµÆðÀ´¡£Ö÷¼ü£¨Primary Key£©ÊÇÒ»¸öÁУ¬ÔÚÕâ¸öÁÐÖеÄÿһÐеÄÖµ¶¼ÊÇΨһµÄ¡£ÔÚ±íÖУ¬Ã¿¸öÖ÷¼üµÄÖµ¶¼ÊÇΨһµÄ¡£ÕâÑù×öµÄÄ¿µÄÊÇÔÚ²»Öظ´Ã¿¸ö±íÖеÄËùÓÐÊý¾ÝµÄÇé¿öÏ£¬°Ñ±í¼äµÄÊý¾Ý½»²æÀ¦°óÔÚÒ»Æð¡£
Çë¿´ "Persons" ±í£º
Id_PLastNameFirstNameAddressCity
1
Adams
John
Oxford Street
London
2
Bush
George
Fifth Avenue
New York
3
Carter
Thomas
Changan Street
Beijing
Çë×¢Ò⣬"Id_P" ÁÐÊÇ Persons ±íÖеĵÄÖ÷¼ü¡£ÕâÒâζ×ÅûÓÐÁ½ÐÐÄܹ»ÓµÓÐÏàͬµÄ Id_P¡£¼´Ê¹Á½¸öÈ˵ÄÐÕÃûÍêÈ«Ïàͬ£¬Id_P Ò²¿ÉÒÔÇø·ÖËûÃÇ¡£
½ÓÏÂÀ´Çë¿´ "Orders" ±í£º
Id_OOrderNoId_P
1
77895
3
2
44678
3
3
22456
1
4
24562
1
5
34764
65
Çë×¢Ò⣬"Id_O" ÁÐÊÇ Orders ±íÖеĵÄÖ÷¼ü£¬Í¬Ê±£¬"Orders" ±íÖÐµÄ "Id_P" ÁÐÓÃÓÚÒýÓà "Persons" ±íÖеÄÈË£¬¶øÎÞÐèʹÓÃËûÃǵÄÈ·ÇÐÐÕÃû¡£
ÇëÁôÒ⣬"Id_P" ÁаÑÉÏÃæµÄÁ½¸ö±íÁªÏµÁËÆðÀ´¡£
ÒýÓÃÁ½¸ö±í
ÎÒÃÇ¿ÉÒÔͨ¹ýÒýÓÃÁ½¸ö±íµÄ·½Ê½£¬´ÓÁ½¸ö±íÖлñÈ¡Êý¾Ý£º
˶©¹ºÁ˲úÆ·£¬²¢ÇÒËûÃǶ©¹ºÁËʲô²úÆ·£¿
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
from Persons, Orders
WHERE Persons.Id_P = Orders.Id_P
½á¹û¼¯£º
LastNameFirstNameOrderNo
Adams
John
22456
Adams
John
24562
Carter
Thomas
77895
Carter
Thomas
44678
SQL JOIN - ʹÓà Join
³ýÁËÉÏÃæµÄ·½·¨£¬ÎÒÃÇÒ²¿ÉÒÔʹÓùؼü´Ê JOIN À´´ÓÁ½¸ö±íÖлñÈ¡Êý¾Ý¡£
Èç¹ûÎÒÃÇÏ£ÍûÁгöËùÓÐÈ˵Ķ¨¹º£¬¿ÉÒÔʹÓÃÏÂÃæµÄ SELECT Óï¾ä£º
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
from Persons
INNER JOIN Orders
ON Persons.Id_P = Orders.Id_P
ORDER BY Persons.LastName
½á¹û¼¯£º
LastNameFirstNameOrderNo
Adams
John
22456
Adams
John
24562
Carter
Thomas
77895
Carter
Thomas
44678
²»Í¬µÄ SQL JOIN
³ýÁËÎÒÃÇÔÚÉÏÃæµÄÀý×ÓÖÐʹÓÃµÄ INNER JOIN£¨ÄÚÁ¬½Ó£©£¬ÎÒÃÇ»¹¿ÉÒÔÆäËû¼¸ÖÖÁ¬½Ó¡£
ÏÂÃæÁгöÁËÄú¿ÉÒÔʹÓÃµÄ JOIN ÀàÐÍ£¬ÒÔ¼°ËüÃÇÖ®¼äµÄ²îÒì¡£
JOIN: Èç¹û±íÖÐÓÐÖÁÉÙÒ»¸öÆ¥Å䣬Ôò·µ»ØÐÐ
LEFT JOIN: ¼´Ê¹ÓÒ±íÖÐûÓÐÆ¥Å䣬Ҳ´Ó×ó±í·µ»ØËùÓеÄÐÐ
RIGHT J
Ïà¹ØÎĵµ£º
ϵͳ»·¾³£ºWindows 7
Èí¼þ»·¾³£ºVisual C++ 2008 SP1 +SQL Server 2005
±¾´ÎÄ¿µÄ£º±àдһ¸öº½¿Õ¹ÜÀíϵͳ
ÕâÊÇÊý¾Ý¿â¿Î³ÌÉè¼ÆµÄ³É¹û£¬ËäÈ»³É¼¨²»¼Ñ£¬µ«ÊÇ×÷ΪÎÒÓÃVC++ ÒÔÀ´±àдµÄ×î´ó³ÌÐò»¹ÊÇ´«µ½ÍøÉÏ£¬ÒÔ¹©²Î¿¼¡£ÓÃVC++ ×öÊý¾Ý¿âÉè¼Æ²¢²»ÈÝÒ×£¬µ«Ò²²»ÊDz»¿ÉÄÜ¡£ÒÔÏÂÊÇÎҵijÌÐò½çÃ棬ºóÃæ ......
from×Ó¾äÖ¸¶¨ÐèÒª½øÐÐÊý¾Ý²éѯµÄ±í£¬ÊÓͼµÈÊý¾ÝÔ´£¬ÓöººÅ·Ö¸ô¡£
from×Ӿ仹¿ÉÒÔÖ¸¶¨Êý¾Ý±í»òÊÓͼ֮¼äµÄÁ¬½ÓÀàÐÍ£¬ÀàÐÍÈ¡¾öÓÚon×Ó¾äÖÐÖ¸¶¨µÄÁ¬½ÓÌõ¼þ¡£
T-SQL¿ÉÒÔÖ§³ÖÔÚfrom×Ó¾äÖÐÖ¸¶¨³ýÊý¾Ý±í»òÊÓͼÍâµÄÆäËû¶ÔÏó¹¹³ÉÅÉÉú±í¡£
ÀýÈ磺select emp.Ô±¹¤±àºÅ£¬emp.Ô±¹¤ÐÕÃû£¬sp.²¿ÃÅÃû³Æ
fr ......
CONVERT
½«Ä³ÖÖÊý¾ÝÀàÐ͵ıí´ïʽÏÔʽת»»ÎªÁíÒ»ÖÖÊý¾ÝÀàÐÍ¡£ÓÉÓÚijЩÐèÇó¾³£Óõ½È¡ÈÕÆÚ¸ñʽµÄ²»Í¬.ÏÖÒÔÏ¿ÉÔÚ
SQL ServerÖС¡½«ÈÕÆÚ¸ñʽ»¯.
SQL Server Ö§³ÖʹÓÿÆÍþÌØËã·¨µÄ°¢À²®ÑùʽÖеÄÊý¾Ý¸ñʽ¡£
ÔÚ±íÖУ¬×ó²àµÄÁ½Áбíʾ½« datetime »ò smalldatetime ת»»Îª×Ö·ûÊý¾ÝµÄ style Öµ¡£¸ø style Öµ¼Ó 100£¬¿É»ñµÃ°üÀ¨Ê ......
exec('selectIDENTITY(int,1,1) as ID,fnum,into #yuecu from store_store where '+@Parameter)
select XX,XX1,XX2 from #yuecu
ÕâÑù´´½¨Ò»¸öÁÙʱ±íÒÔºóÎÒÔÙÏë´ÓÁÙʱ±íÖÐÈ¡Êý¾ÝÌáʾ¶ÔÏóÃû#yuecu&n ......