SQL命令和SQL語句


Mysql客戶端命令

\q:exit   退出

所有的SQL語句都是以分號結束的.

\c:clear   中斷不想執行的SQL語句

\G:格式化顯示查詢的結果(key:value)

\T:tee  記錄日志

\u:use 切換數據庫

\h:help 查看幫助信息

\s:status  查看當前庫詳細信息

\ .:source 導入SQL文件中的數據

Mysql常用命令行

#登錄mysql:(#注意不要把密碼寫到命令行)

mysql -uroot -p

-S  指定socket文件位置	
mysql -uroot -p -S /application/mysql/tmp/mysql.sock 

注:
如果是編譯安裝的mysql,可以省略-S 
如果其他方式呢,加上-S 

-h  指定鏈接的地址
mysql -uroot -p -h 10.0.0.51 

-P  指定鏈接的端口號

mysql -uroot -p -h 10.0.0.51  -P 3307

-e  免交互式執行mysql內部命令

mysql -uroot -p -e "select user,host,password from mysql.user;"

<  導入SQL腳本到mysql中

mysql -uroot -p </root/world.sql


mysqladmin命令

1.修改密碼,設置密碼:password
mysqladmin -uroot -p舊密碼 password '新密碼'

2.關閉MySQL服務:shutdown
mysqladmin -uroot -p密碼 -S socket文件 shutdown

3.庫外建庫:create
mysqladmin -uroot -p密碼 create zls

mysql -uroot -p123 -e 'create database zls2'

4.庫外刪除數據庫:drop
[root@db01 ~]# mysqladmin -uroot -p123 drop zls1
Do you really want to drop the 'zls1' database [y/N] y
Database "zls1" dropped

5.查看配置文件所有的默認參數:variables
mysqladmin -uroot -p123 variables

6.檢測MySQL進程是否存活:ping
mysqladmin -uroot -p123 ping

7.查看數據庫 慢查詢,負載信息:status
mysqladmin -uroot -p123 status

8.重載授權表,刷新緩存主機:reload
mysqladmin -uroot -p123 reload

9.刷新binlog日志
mysqladmin -uroot -p123 flush-log

SQL語句:

​ DDL:數據定義語言

​ 庫對象:庫名字,庫屬性

​ 開發規范:庫名小寫

1.針對庫的操作:
建庫:
create database bgx;
create schema long;
create database if not exists long;
create database if not exists huan collate utf8_general_ci charset utf8;
刪庫:
drop database long;
修改庫:
alter database huan charset utf8;
2.針對表的操作:
###### 建表:
	create table huan(id int);
	create table huan2( id int, name varchar(10), gender enum('m','f','oldtian'));
		
	create table huan( 
	id int, 
	name varchar(10), 
	age tinyint, 
	gender enum('f','m'), 
	cometime datetime);
表名:student
		sid
		sname
		sage
		sgender
		scometime

	數據類型
	整型:
	tinyint(m)	 最小整數 -128 ~ 127
	smallint(m)  2個字節  范圍(-32768~32767)
	mediumint(m) 3個字節  范圍(-8388608~8388607)
	int(m) 		 4個字節  整數 -2^31 ~ 2^31 -1
	bigint(m)    8個字節  范圍(+-9.22*10的18次方)
	
	字符串:
	varchar:	字符類型 (變長)
	char: 	 	字符類型 (定長)
	enum:   	枚舉類型
	浮點型:
	float(m,d):  單精度浮點數  8位精度(4字節)  m總個數,d小數位
	double(m,d): 雙精度浮點型  16位精度(8字節) m總個數,d小數位
	日期時間類型:
	date:        日期'2019-12-12'
	time:        時間'12:30:30'
	datetime:   時間類型 年月日時分秒
	timestamp:   自動存儲記錄修改時間
數據屬性:
	    null:                空(數據列可包含null值)
	    not null: 			非空
		primary key: 		主鍵(唯一且非空的)
		auto_increment: 	自增(此列必須是:primary key或者unique key)
		unique key: 		單獨的唯一的
		default: 			默認值
		unsigned: 			無符號,非負數
		character set name   指定一個字符集
		comment: 			注釋
修改表:
	添加字段:
#添加字段(默認添加到最后)
alter table student add 字段 varchar(10);
#在表頭添加字段
alter table student add 字段 varchar(10) first;
#在指定字段之后添加字段
alter table student add 字段 varchar(10) after 字段;
#添加多個字段
alter table student add xiejun varchar(10),add lixin varchar(20);
#刪除字段
alter table student drop xiejun;		
#修改字段的數據類型:(只能支持單個修改,不支持多個)
alter table student modify 字段 int;			
#修改字段名:
alter table student change lixin xiewang int;			
#修改字段名和數據類型
alter table student change xiewang lixin char(10);			
#修改表名
alter table student rename stu;


DCL:數據控制語言 control

grant
grant:
			grant all on *.* to root@'%' identified by '123';
			max_queries_per_hour:一個用戶每小時可發出的查詢數量
			max_updates_per_hour:一個用戶每小時可發出的更新數量
			max_connections_per_hour:一個用戶每小時可連接到服務器的次數
			max_user_connections:允許同時連接數量
revoke:
		revoke select on *.* from root@'%';

DML:數據操作語言

grant insert,update,delete,select
insert
insert:插入數據
	#不規范寫法
mysql> insert into huan values(1,'wu',18,'f',now());
	
	#規范寫法,插入一條數據
mysql> insert into huan(name,age,gender) values('ding',28,'m');
	
	#規范寫法,插入多條數據
mysql> insert into huan(name,age,gender) values('long',18,'f'),('liu',84,'f');
update
update:修改數據
	#危險,整列全都修改成f
	update test.huan set gender='f';
	
	注意:使用update時,必須要接條件(where)
	update test.huan set gender='m' where id=7;
	
	#就是修改整列內容
	update test.huan set name='boy' where 1=1;
delete
delete:刪除數據
#危險,刪除整張表的數據
delete from test.huan;
注意:使用delete時,必須接條件(where)
delete from test.huan where id=13;

#就是修改整表內容
delete from test.huan where 1=1;

刪除列(字段):
alter table test.huan drop name;
使用update代替delete做偽刪除:
	1.添加一個狀態列(一段),表示該行數據的狀態
	alter table test.huan add status enum('0','1') default '1';
	
	2.如何刪除數據?
	update test.huan set status='0' where id=9;
	
	3.如何查詢數據?
	select * from test.huan where status='1';

DQL:數據查詢語言

select:查詢數據(awk)
    #查看表中所有內容(危險)
	select * from test.huan;
	
	#如果要查詢所有數據的總量,使用count
	select count(*) from test.huan;
	
	#查看某幾列中的內容
	select gender,age from test.huan;

	#查詢,接多條件
	select gender,age from test.huan where age=18 and gender='f';
	
	mysql> use world

	mysql> show tables;
	+-----------------+
	| Tables_in_world |
	+-----------------+
	| city            |		城市
	| country         |		國家
	| countrylanguage |		國家語言
	+-----------------+
	#查看city表中所有的內容
	select * from city;
	#查詢city表中的字段(表結構)
	desc city;


​ order by :排序
​ #按照人口數量排序(升序)
​ select * from city order by population;

	#按照人口數量排序(降序)
	select * from city order by population desc;


​ #按照人口數量排序,前十的(limit)
​ select * from city order by population limit 10;

	#按照步長60查找數據(翻頁)
	select * from world.city limit 60,60
	
	where接條件: > < = , >= <= (!= <>  不等於),like ,and,or
	
	=:精確查詢
	> < = , >= <= != :范圍查詢
	like:模糊查詢
	
	#模糊查詢
	select * from world.city where countrycode like '%H%';

	#or
	select * from world.city where countrycode='CHN' or countrycode='USA';
	
	#in
	select * from world.city where countrycode in ('CHN','USA');
											   not in
	#union all (聯合查詢)
	select * from world.city where countrycode='USA' union all select * from world.city where countrycode='CHN';
#select高級用法,多表聯查
查看人口超過100萬人口的城市,國家名國家代碼,國土面積

mysql> select city.name,city.countrycode,country.name,country.SurfaceArea
    -> from city join country
    -> on city.countrycode=country.code
    -> where city.population > 1000000
    order by city.population
    desc limit 10,10;
 #傳統方式多表連查
    select city.name,city.population,country.name 
    from city,country 
    where city.countrycode=country.code 
    and city.population 1000000;
    ORDER BY population;
 
#select 內連接(用的最多,最好用)
#查詢龍在曾的課程里獲得的分數
select student.sno,student.sname,student.sage,student.class,
teacher.depart,teacher.prof,
score.mark,teacher.tname,
course.cname
from score  
join student on score.sno=student.sno
join course on score.cno=course.cno
join teacher on course.tno=teacher.tno
where student.sname='龍'
and teacher.tname='曾';
 
#union all (聯合查詢),速度更快 union all 
        select * from world.city where countrycode='USA' union all select * from world.city where countrycode='CHN';

聚合函數:GROUP BY + 聚合函數 (COUNT(),MAX(),MIN(),AVG(),SUM())

(1) COUNT(),統計數量
  統計city表中城市的個數.
  SELECT COUNT(*) FROM city;
  使用* 是直接查找主鍵,因為count是直接查主鍵的
 (2)統計一下各個國家的城市個數     (原理是以國家的名字來分,一個相同的國家名就+1)
 (還有一種想法是,數個數,所以使用count(name),然后什么什么的,加上group by,就是形容詞就是放在group by 后面)
 mysql> select countrycode,count(name) as a from city group by countrycode order by a desc limit 10;
+-------------+-----+
| countrycode | a   |
+-------------+-----+
| CHN         | 363 |
| IND         | 341 |
| USA         | 274 |
| BRA         | 250 |
| JPN         | 248 |
| RUS         | 189 |
| MEX         | 173 |
| PHL         | 136 |
| DEU         |  93 |
| IDN         |  85 |
+-------------+-----+
 
 (3)統計一下中國 , 各省的 人口 總和(SUM()).
 SELECT district, SUM(population) 
 FROM city  
 WHERE countrycode='chn' 
 GROUP BY district;
 
 mysql> select District,sum(population) from city  where countrycode='chn' group by district; ####group by 一定要放在最后面
 
 (4)統計 每個國家的人口總數
 SELECT countrycode,SUM(population) 
 FROM city
 GROUP BY countrycode;

外鏈接

#左連接
mysql> select teacher.tname,course.cname 
    -> from teacher 
    -> left join course 
    -> on teacher.tno=course.tno
    -> and teacher.tname='曾';
+-------+-----------+
| tname | cname     |
+-------+-----------+
| 曾    | 數據庫    |
| 田    | NULL      |
| 徐    | NULL      |
+-------+-----------+
3 rows in set (0.00 sec)
 
#右連接
mysql> select teacher.tname,course.cname 
    -> from teacher 
    -> right join course 
    -> on teacher.tno=course.tno
    -> and teacher.tname='曾';
+-------+-----------+
| tname | cname     |
+-------+-----------+
| 曾    | 數據庫    |
| NULL  | 架構      |
| NULL  | 計算機    |
+-------+-----------+
 

子查詢(不推薦,效率太低)

mysql> select name from country where code=(select countrycode from city where population<100);
+----------+
| name     |
+----------+
| Pitcairn |
+----------+
1 row in set (0.00 sec
{1}
我們可以用多表聯查來搞定
mysql> select c.name
from country as c 
join city as t 
on c.code=t.countrycode
where t.population < 100 ;
+----------+
| name     |
+----------+
| Pitcairn |
+----------+
1 row in set (0.01 sec)
 

視圖

一個視圖就是一個查詢方法
create view test as
sql語句

然后形成一個視圖
下次可以直接查看 select * from test (test就是一個視圖了,可以看成一張正常的表)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM