一:SQL語句 - 系統的擼一遍MySQL

MySQL中的SQL

SQL(Structure Query Language)結構化查詢語言,MySQL並無徹底實現ANSI/ISO的SQL標準,而且在基礎上增長了一些擴展SQL語句好比LIMIT等。sql

SQL語句主要分爲三類:

DDL語句、DML語句、DCL語句數據庫

DDL(Data Definition Language)語句:

主要用於定義數據庫、表結構、索引等內容,經常使用語句以下:spa

建立數據庫:code

CREATE DATABASE twitter CHARSET=utf8;

刪除數據庫:排序

DROP DATABASE twitter;

建立表:索引

create table `user`(
    id int(11),
    title varchar(50)
);

刪除表:ip

DROP TABLE user;

 增長字段:it

ALTER TABLE user ADD COLUMN age tinyint(4) AFTER name;

刪除字段:io

ALTER TABLE user DROP COLUMN age;

修改字段:table

ALTER TABLE user MODIFY name varchar(20);

修改字段名:

ALTER TABLE user CHANGE name nickname varchar(50);

增長索引:

ALTER TABLE user ADD INDEX idx_age(age);

刪除索引:

ALTER TABLE user DROP INDEX idx_age;

 DML(Data Manipulation Language)語句:

主要用於數據庫表數據的增刪改查等操做。

增長數據:

INSERT INTO user(id, name) VALUES(1, '小明'), (2, '小紅');

刪除數據:

//刪除一張表數據
DELETE FROM user WHERE id = 1;
//同時刪除多張
DELETE a,b FROM user AS a, user2 AS b WHERE a.id = 1 AND b.id = 2;

修改數據:

//修改一張表
UPDATE user SET age = 10 WHERE id = 1;
//同時修改多個表
UPDATE user, user2 SET user.age = 10, user2.age = 20;

查詢數據:

//簡單查詢
SELECT id,name FROM user;
//查詢去重
SELECT distinct name,id FROM user;
//查詢總數
SELECT COUNT(1) FROM user;
//分頁排序
SELECT id,name FROM user ORDER BY id DESC LIMIT 0, 10;
//分組篩選
SELECT name, COUNT(1) as t FROM user GROUP BY age HAVING t > 10;
//聯合查詢 不加ALL會隱藏重複數據
SELECT id,name FROM user UNION ALL SELECT id,name FROM user2;
//子查詢
SELECT id,name FROM user WHERE id IN(SELECT id FROM user2);
SELECT id,name FROM user WHERE id = (SELECT id FROM user2 LIMIT 1);
//鏈接查詢查詢
SELECT * FROM user INNER JOIN user2 ON user.name = user2.name;
SELECT * FROM user LEFT JOIN user2 ON user.name = user2.name;

DCL(Data Control Language)語句:

增長帳號並賦予權限:

GRANT SELECT,INSERT,DELETE ON twitter.* TO 'username@127.0.0.1' IDENTIFIED BY 'password';

修改權限:

ROVOKE SELECT ON twitter.* FROM 'username@127.0.0.1';
相關文章
相關標籤/搜索