DML(Data Manipulation Language):INSERT, DELETE, UPDATE, SELECT
INSERT [INTO] tbl_name [(col1,...)] {VALUES|VALUE} (val1, ...),(...),...
假如有上面這張表
插入一行數據:insert students values(1,'xijinping',51,'zhonglanhai','m'); 字符串必須加引號,數字不能加引號
同時插入多行數據:insert students (id,name) values (2,'hujingtao'),(3,'jiangzeming');
SELECT:
查看一張表的全部字段:select * from students;
只查看指定的字段:select id,name from students;
將字段id取個別名:select id as stuid,name from students;
WHERE clause:用於指明挑選條件
col_name 操作符 value, 例如:age > 30
操作符(1) :>, <, >=, <=, ==, !=
例如:select * from students where id=1;
select * from students where name='jiangzemin'; 注意:後面的字符串要加引號,是否區分大小寫,取決於字符類型,如果是
binary或者varbinary則區分大小寫,char或者varchar則不需要區分大小寫
組合條件:or,and,not
select name,age from students where age>=30 and age<=50;
select name,age from students where age between 30 and 50; 跟上面的語句是一個意思
操作符 :BETWEEN ... AND ... LIKE 'PATTERN' RLIKE 'PATTERN'(正則表達式對字符串做模式匹配) IS NULL
IS NOT NULL
select name from students where name like '%ji%'; 注意像like,rlike這種查詢方式性能極低
%:任意長度的任意字符 _:任意單個字符
select name from students where name rlike 'min$';
select name,age from students where age is null;
select id,name from students order by name; 根據name字段中的第一個字母排序,默認升序,加desc改為降序
注意其實執行DML語句首先都執行了select查詢
DELETE:刪除是相對應於行的
(1) DELETE FROM tbl_name WHERE where_condition
(2) DELETE FROM tbl_name [ORDER BY ...] [LIMIT row_count]
delete from students; (刪除表的所有行)
delete from students where age is null;
技巧 1. 快速創建相同結構的表,包括索引:MariaDB [test1]> create table a like students;
2.快速創建一個相同結構的表,但是不創建索引:MariaDB [test1]> create table b select * from students limit 0;
[root@localhost ~]# for i in {1..100}; do AGE=$[$RANDOM%100]; mysql -e "insert test1.a (id,name,age) values
($i,\"stu$i\",$AGE);"; done 為a這張表加入一些數據
delete from a order by age desc limit 20;
UPDATE:
update a set age=age-5 order by id desc limit 10;
update a set age=age-5 where name not like 'stu__';
用戶賬號及權限管理:
用戶賬號:'username'@'host'
禁止檢查主機名:在my.cnf配置文件中的[mysqld]段添加skip_name_resolve = ON 一般都得添加此選項以提升性能
創建用戶賬號:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
例如:create user 'testuser'@'192.168.%.%' identified by 'testpass'; 記得刷新用戶授權表flush privileges;
刪除用戶賬號:DROP USER 'user'@'host' [, user@host] ...
例如:drop user 'testuser'@'192.168.%.%';
查看用戶授權表命令:select * from mysql.user\G;
授權:GRANT priv_type,... ON [object_type] db_name.tbl_name TO 'user'@'host' [IDENTIFIED BY 'password'];
例如:grant select,insert on test1.students to 'testuser'@'192.168.%.%';
查看指定用戶所獲得的授權:SHOW GRANTS FOR 'user'@'host'; SHOW GRANTS FOR CURRENT_USER;
回收權限:REVOKE priv_type, ... ON db_name.tbl_name FROM 'user'@'host';
例如:revoke insert on test1.students from 'testuser'@'192.168.%.%';
注意:MariaDB服務進程啟動時,會讀取mysql庫的所有授權表至內存中
(1) GRANT或REVOKE命令等執行的權限操作會保存於表中,MariaDB此時一般會自動重讀授權表,權限修改會立即生效
(2) 其它方式實現的權限修改,要想生效,必須手動運行FLUSH PRIVILEGES命令
mariadb安裝完後密碼是空的,這是不安全的,看下圖;
可以使用該命令完成root密碼設定:[root@localhost ~]# mysql_secure_installation