sqlÖÐÅÌÎÊÖظ´Êý¾ÝÔõôд
ÔÚ sql ÖУ¬ÅÌÎÊÖظ´Êý¾ÝµÄÁ½ÖÖÒªÁìÊÇ£ºÊ¹Óà group by ×Ӿ佫Êý¾Ý·Ö×é²¢ÅÌËãÿ×éµÄÖظ´´ÎÊý¡£Ê¹Óà except ×Ó¾ä´Ó°üÀ¨ËùÓÐÊý¾ÝµÄ×ÓÅÌÎÊÖÐɨ³ý°üÀ¨Öظ´Êý¾ÝµÄ×ÓÅÌÎÊ¡£
SQL ÖÐÅÌÎÊÖظ´Êý¾ÝµÄÒªÁì
ÔÚ SQL ÖУ¬ÅÌÎÊÖظ´Êý¾ÝµÄÒªÁìÓÐÁ½ÖÖ£º
1. GROUP BY ×Ó¾ä
¹¦Ð§£º½«Êý¾Ý·Ö×é²¢·µ»Øÿ×éµÄ¾ÛºÏЧ¹û£¨ÀýÈç¼ÆÊý£©¡£
Óï·¨£º SELECT column_list, COUNT(*) AS count FROM table_name GROUP BY column_list
Ó÷¨£ºÊ¹Óà COUNT(*) ¾ÛºÏº¯ÊýÅÌËãÿ×éµÄÖظ´´ÎÊý¡£
ÀýÈ磬ÅÌÎÊ orders ±íÖÐÖظ´·ºÆðµÄ product_id£º
SELECT product_id, COUNT(*) AS count FROM orders GROUP BY product_id HAVING COUNT(*) > 1;
µÇ¼ºó¸´ÖÆ
2. EXCEPT ×Ó¾ä
¹¦Ð§£º´ÓÒ»¸öЧ¹û¼¯ÖÐɨ³ýÁíÒ»¸öЧ¹û¼¯ÖаüÀ¨µÄÐС£
Óï·¨£º SELECT column_list FROM table_name EXCEPT SELECT column_list FROM table_name
Ó÷¨£º½«Ò»¸ö°üÀ¨ËùÓÐÊý¾ÝµÄ×ÓÅÌÎÊ×÷ΪµÚÒ»¸öÑ¡ÔñÁÐ±í£¬È»ºóʹÓà EXCEPT ½«°üÀ¨Öظ´Êý¾ÝµÄ×ÓÅÌÎÊ×÷ΪµÚ¶þ¸öÑ¡ÔñÁÐ±í¡£
ÀýÈ磬ÅÌÎÊ orders ±íÖÐÖ»·ºÆðÒ»´ÎµÄ product_id£º
SELECT product_id FROM orders EXCEPT SELECT product_id FROM orders GROUP BY product_id HAVING COUNT(*) > 1;
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇsqlÖÐÅÌÎÊÖظ´Êý¾ÝÔõôдµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡