SQL簡單使用-基礎篇
先建立一個數據表便於做增刪改查的練習,這裏就直接將創建表的語句寫出來先執行。後面在學習如何建立數據表
SET NAMES utf8; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for `websites` -- ---------------------------- DROP TABLE IF EXISTS `websites`; CREATE TABLE `websites` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` char(20) NOT NULL DEFAULT ‘‘ COMMENT ‘站點名稱‘, `url` varchar(255) NOT NULL DEFAULT ‘‘, `alexa` int(11) NOT NULL DEFAULT ‘0‘ COMMENT ‘Alexa 排名‘, `country` char(10) NOT NULL DEFAULT ‘‘ COMMENT ‘國家‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of `websites` -- ---------------------------- BEGIN; INSERT INTO `websites` VALUES (‘1‘, ‘Google‘, ‘https://www.google.cm/‘, ‘1‘, ‘USA‘), (‘2‘, ‘淘寶‘, ‘https://www.taobao.com/‘, ‘13‘, ‘CN‘), (‘3‘, ‘菜鳥教程‘, ‘http://www.runoob.com/‘, ‘4689‘, ‘CN‘), (‘4‘, ‘微博‘, ‘http://weibo.com/‘, ‘20‘, ‘CN‘), (‘5‘, ‘Facebook‘, ‘https://www.facebook.com/‘, ‘3‘, ‘USA‘); COMMIT; SET FOREIGN_KEY_CHECKS = 1;
1.select 用於查詢數據
示例:select * from websites;
查詢創建的websites表數據。 註意後面的分號,分號表示一段SQL命令的結束。select * from websites where name=‘淘寶‘;
查詢websites表中的‘淘寶’的數據, 號表示查詢這個websites表的所有數據。這裏號可以寫成表的某一列。select name from websites; 或 select name from websites where country=‘CN‘;
2.select disinct 用於返回唯一不同的值。
示例:select distinct country from websites;
3.where 子句用於提取那些指定標準的數據
運算符
、<、=、!=、<>、>=、<= 大於/小於/等於/不等於/大於等於/小於等於
between 某個範圍內
in 指定針對某個列的多個可能值
like 搜索某種模式
4.and & or
and 如果第一個條件成立和第二個條件都成立,則and顯示一條記錄,
or 如果第一個條件和第二個條件有一個條件成立,則顯示一條一條記錄;
示例:
SELECT * FROM Websites WHERE country=‘CN‘ AND alexa > 50; SELECT * FROM Websites WHERE country=‘CN‘ or alexa > 50;
結合運用select * from websites where alexa >15 and ( country=‘CN‘ or country=‘US‘ );
5.order by 對於查詢的數值進行排序,order by 升序, 加上desc為降序
示例:
select * from websites order by alexa; 以alexa列的數值進行升序排序
select * from websites order by country,alexa desc; 以country和Alexa的數值進行降序排序(其中由於country在前,所以country優先級高於Alexa)
6.insert into 向表中插入新數據。
示例:insert into websites (name,url,alexa,country) values (‘百度‘,‘https://www.baidu.com/‘,‘4‘,‘CN‘)
7.update 用於更新表中已存在的記錄
示例:update websites set alexa =‘5000‘ , country =‘USA‘ where name =‘菜鳥教程‘;
註意如果不加where則會將websites整張表的數據都改了。所以在實際生產環境中管理員都會對update使用進行限制,如果使用update時沒有加上where則會報錯
- delete、drop、truncate 刪除數據 (其中drop與truncate刪除數據不可恢復,所以在使用前切記慎重,做好數據備份準備)
delete 用於刪除表中數據(可以刪除整張表的數據或者表中某一段數據,)delete from websites where name=‘菜鳥教程‘; delete table websites; 或 delete * from websites;
drop tables websites; 刪除websites數據表
drop database mysql; 刪除mysql數據庫
truncate tables websites刪除表數據,表的框架還保留,但數據不可恢復,這是與delete的區別點
SQL簡單使用-基礎篇