sqlÖеÄunionÊÇʲôÒâ˼
sql ÖÐµÄ union ÔËËã·ûÓÃÓںϲ¢±íÖеÄÊý¾Ý£¬ÌصãΪ£ººÏ²¢±í¡¢ÒªÇóÁÐÆ¥Åä¡¢±£´æÖظ´ÐС£ÓÃ;°üÀ¨£ººÏ²¢»¥²¹Êý¾Ý¡¢²éÕÒÖظ´Êý¾Ý¡¢½¨Éè»ã×ܱ¨±íºÍÏû³ýÖظ´Êý¾Ý¡£Ê¾Àý£ºselect customer_id, first_name, last_name from customers union select customer_id, first_name, last_name from orders; ½«ºÏ²¢ customers ºÍ orders ±íµÄ¿Í»§Êý¾Ý£¬°üÀ¨Öظ´ÐС£
SQL ÖÐµÄ UNION
UNION ÊÇ SQL ÖеÄÔËËã·û£¬ÓÃÓںϲ¢Á½¸ö»ò¸ü¶à±íÖеÄÊý¾Ý¡£Ëü½«ÊäÈë±íÖеÄÐи½¼ÓÔÚÒ»Æ𣬽¨ÉèÒ»ÕÅеÄЧ¹û±í¡£
Óï·¨
SELECT ÁÐÃû1, ÁÐÃû2, ... FROM ±í1 UNION SELECT ÁÐÃû1, ÁÐÃû2, ... FROM ±í2;
µÇ¼ºó¸´ÖÆ
Ìصã
ºÏ²¢±í£ºUNION ºÏ²¢Á½¸ö»ò¸ü¶à¸ö±íµÄÐС£
ÁÐÆ¥Å䣺Ҫ±»ºÏ²¢µÄ±í±ØÐè¾ßÓÐÏàͬµÄÁÐÊýÄ¿ºÍÊý¾ÝÀàÐÍ¡£
Ч¹û˳Ðò£ºÐ§¹û±íÖеÄÐÐƾ֤ÊäÈë±íµÄ˳ÐòÅÅÁС£
Öظ´ÐУºÓë INTERSECT ºÍ EXCEPT ²î±ð£¬UNION »á±£´æÖظ´ÐС£
ÓÃ;
UNION Ö÷ÒªÓÃÓÚÒÔÏÂÇéÐΣº
ºÏ²¢À´×Ô²î±ð±íµÄ»¥²¹Êý¾Ý£ºÀýÈ磬ºÏ²¢Á½¸ö°üÀ¨²î±ð×ֶεĿͻ§±íÒÔ½¨Éè¸üÖÜÈ«µÄÊÓͼ¡£
²éÕÒ²î±ð±íÖеÄÖظ´Êý¾Ý£ºÊ¹Óà UNION ALL£¨ÎÞ DISTINCT£©À´²éÕÒ¿ç±íµÄÖظ´ÐС£
½¨Éè»ã×ܱ¨±í£ºÎ´À´×Ô¶à¸ö±íµÄ»ã×ÜÊý¾ÝºÏ²¢ÎªÒ»¸ö±í¡£
Ïû³ýÖظ´Êý¾Ý£ºÔÚʹÓà UNION ֮ǰ£¬Ê¹Óà DISTINCT Òªº¦×Ö¿ÉÒÔÏû³ýÖظ´ÐС£
ʾÀý
ÒÔÏÂʾÀý½«Á½¸öÃûΪ customers ºÍ orders µÄ±íµÄ¿Í»§Êý¾ÝºÏ²¢ÎªÒ»¸öЧ¹û±í£º
SELECT customer_id, first_name, last_name FROM customers UNION SELECT customer_id, first_name, last_name FROM orders;
µÇ¼ºó¸´ÖÆ
Ч¹û±í½«°üÀ¨Á½¸ö±íµÄ¿Í»§ÐÅÏ¢£¬°üÀ¨Öظ´ÐС£
ÒÔÉϾÍÊÇsqlÖеÄunionÊÇʲôÒâ˼µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡