SQL Ö÷¼üµÄÓ÷¨
Ö÷¼ü (Primary Key) ÖеÄÿһ±Ê×ÊÁ϶¼ÊDZí¸ñÖеÄΨһֵ¡£»»ÑÔÖ®£¬ËüÊÇÓÃÀ´¶ÀÒ»ÎÞ¶þµØÈ·ÈÏÒ»¸ö±í¸ñÖеÄÿһÐÐ×ÊÁÏ¡£Ö÷¼ü¿ÉÒÔÊÇÔ±¾×ÊÁÏÄÚµÄÒ»¸öÀ¸Î»£¬»òÊÇÒ»¸öÈËÔìÀ¸Î» (ÓëÔ±¾×ÊÁÏûÓйØϵµÄÀ¸Î»)¡£Ö÷¼ü¿ÉÒÔ°üº¬Ò»»ò¶à¸öÀ¸Î»¡£µ±Ö÷¼ü°üº¬¶à¸öÀ¸Î»Ê±£¬³ÆΪ×éºÏ¼ü (Composite Key)¡£
Ö÷¼ü¿ÉÒÔÔÚ½¨ÖÃбí¸ñʱÉ趨 (ÔËÓà CREATE TABLE Óï¾ä)£¬»òÊÇÒԸıäÏÖÓеıí¸ñ¼Ü¹¹·½Ê½É趨 (ÔËÓà ALTER TABLE)¡£
ÒÔϾټ¸¸öÔÚ½¨ÖÃбí¸ñʱÉ趨Ö÷¼üµÄ·½Ê½£º
MySQL:
CREATE TABLE Customer
(SID integer,
Last_Name varchar(30),
First_Name varchar(30),
PRIMARY KEY (SID));
Oracle:
CREATE TABLE Customer
(SID integer PRIMARY KEY,
Last_Name varchar(30),
First_Name varchar(30));
SQL Server:
CREATE TABLE Customer
(SID integer PRIMARY KEY,
Last_Name varchar(30),
First_Name varchar(30));
ÒÔÏÂÔòÊÇÒԸıäÏÖÓбí¸ñ¼Ü¹¹À´É趨Ö÷¼üµÄ·½Ê½£º
MySQL:
ALTER TABLE Customer ADD PRIMARY KEY (SID);
Oracle:
ALTER TABLE Customer ADD PRIMARY KEY (SID);
SQL Server:
ALTER TABLE Customer ADD PRIMARY KEY (SID);
Çë×¢Ò⣬ÔÚÓÃALTER TABLEÓï¾äÀ´Ìí¼ÓÖ÷¼ü֮ǰ£¬ÎÒÃÇÐèҪȷÈϱ»ÓÃÀ´µ±×öÖ÷¼üµÄÀ¸Î»ÊÇÉ趨Ϊ ¡ºNOT NULL¡» £»Ò²¾ÍÊÇ˵£¬ÄǸöÀ¸Î»Ò»¶¨²»ÄÜûÓÐ×ÊÁÏ¡£
Ïà¹ØÎĵµ£º
µ½Ä¿Ç°ÎªÖ¹£¬ÎÒÃÇÒÑѧµ½ÈçºÎ½åÓÉ SELECT ¼° WHEREÕâÁ½¸öÖ¸Á×ÊÁÏÓɱí¸ñÖÐ×¥³ö¡£²»¹ýÎÒÃÇÉÐδÌáµ½ÕâЩ×ÊÁÏÒªÈçºÎÅÅÁС£ÕâÆäʵÊÇÒ»¸öºÜÖØÒªµÄÎÊÌâ¡£ÊÂʵÉÏ£¬ÎÒÃǾ³£ÐèÒªÄܹ»½«×¥³öµÄ×ÊÁÏ×öÒ»¸öÓÐϵͳµÄÏÔʾ¡£Õâ¿ÉÄÜÊÇÓÉСÍù´ó (ascending) »òÊÇÓÉ´óÍùС(descending)¡£ÔÚÕâÖÖÇé¿öÏ£¬ÎÒÃǾͿÉÒÔÔËÓà ORDER BYÕâ¸öÖ¸ÁîÀ´´ïµ½ ......
ÔÚÉÏÒ»Ò³ÓÐÌáµ½£¬COUNT ÊǺ¯ÊýÖ®Ò»¡£ÓÉÓÚËüµÄʹÓù㷺£¬ÎÒÃÇÔÚÕâÀïÌرðÌá³öÀ´ÌÖÂÛ¡£»ù±¾ÉÏ£¬COUNT ÈÃÎÒÃÇÄܹ»Êý³öÔÚ±í¸ñÖÐÓжàÉÙ±Ê×ÊÁϱ»Ñ¡³öÀ´¡£ËüµÄÓï·¨ÊÇ£º
SELECT COUNT("À¸Î»Ãû")
from "±í¸ñÃû"
¾ÙÀýÀ´Ëµ£¬ÈôÎÒÃÇÒªÕÒ³öÎÒÃǵÄʾ·¶±í¸ñÖÐÓм¸±Ê store_name À¸²»ÊÇ¿Õ°×µÄ×ÊÁÏʱ£¬
Store_Information ±í¸ñ
store ......
½ÓÏÂÀ´£¬ÎÒÃÇÌÖÂÛ alias (±ðÃû) ÔÚ SQL ÉϵÄÓô¦¡£×î³£Óõ½µÄ±ðÃûÓÐÁ½ÖÖ£º À¸Î»±ðÃû¼°±í¸ñ±ðÃû¡£
¼òµ¥µØÀ´Ëµ£¬À¸Î»±ðÃûµÄÄ¿µÄÊÇΪÁËÈà SQL ²úÉúµÄ½á¹ûÒ׶Á¡£ÔÚ֮ǰµÄÀý×ÓÖУ¬ ÿµ±ÎÒÃÇÓÐÓªÒµ¶î×ܺÏʱ£¬À¸Î»Ãû¶¼ÊÇ SUM(sales)¡£ ËäÈ»ÔÚÕâ¸öÇé¿öÏÂûÓÐʲôÎÊÌ⣬¿ÉÊÇÈç¹ûÕâ¸öÀ¸Î»²»ÊÇÒ»¸ö¼òµ¥µÄ×ܺϣ¬¶øÊÇÒ»¸ö¸´ÔӵļÆË㣬 ......
ºÍ UNION Ö¸ÁîÀàËÆ£¬ INTERSECT Ò²ÊǶÔÁ½¸ö SQL Óï¾äËù²úÉúµÄ½á¹û×ö´¦ÀíµÄ¡£²»Í¬µÄµØ·½ÊÇ£¬ UNION »ù±¾ÉÏÊÇÒ»¸ö OR (Èç¹ûÕâ¸öÖµ´æÔÚÓÚµÚÒ»¾ä»òÊǵڶþ¾ä£¬Ëü¾Í»á±»Ñ¡³ö)£¬¶ø INTERSECT Ôò±È½ÏÏñ AND ( Õâ¸öÖµÒª´æÔÚÓÚµÚÒ»¾äºÍµÚ¶þ¾ä²Å»á±»Ñ¡³ö)¡£ UNION ÊÇÁª¼¯£¬¶ø INTERSECT Êǽ»¼¯¡£
INTERSECT µÄÓï·¨ÈçÏ£º
[SQLÓï¾ä ......
ÓеÄʱºò£¬ÎÒÃÇÓÐÐèÒª½«Óɲ»Í¬À¸Î»»ñµÃµÄ×ÊÁÏ´®Á¬ÔÚÒ»Æð¡£Ã¿Ò»ÖÖ×ÊÁϿⶼÓÐÌṩ·½·¨À´´ïµ½Õâ¸öÄ¿µÄ£º
MySQL: CONCAT()
Oracle: CONCAT(), ||
SQL Server: +
CONCAT() µÄÓï·¨ÈçÏ£º
CONCAT(×Ö´®1, ×Ö´®2, ×Ö´®3, ...): ½«×Ö´®1¡¢×Ö´®2¡¢×Ö´®3£¬µÈ×Ö´®Á¬ÔÚÒ»Æð¡£Çë×¢Ò⣬OracleµÄCONCAT()Ö»ÔÊÐíÁ½¸ö²ÎÊý£»»»ÑÔÖ®£¬Ò ......