shell> mysql -h host -u user -p
Enter password: *******
参数 | 描述 |
---|---|
-h | 地址,如果本地可以省略 |
-u | 用户名 |
-p | 密码 |
mysql> QUIT
大小写不敏感
SELECT VERSION(), CURRENT_DATE;
# 查看笨笨和时间
SELECT SIN(PI()/4), (4+1)*5;
# 把mysql当成计算器
在如果想退出多行输入,可以使用\c
mysql> SELECT
-> USER()
-> \c
SHOW DATABASES;
# 只显示有权限进入的数据库
USE test
# 选择数据库
GRANT ALL ON menagerie.* TO 'your_mysql_name'@'your_client_host';
# 授权使用数据库
数据库大小写敏感,而SQL语句不敏感
CREATE DATABASE menagerie;
USE menagerie
# 进入数据库
mysql -h host -u user -p menagerie
# 连接到指定数据库,不然每次都要使用use
来进入
SHOW TABLES;
# 查看所有表
CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); # 创建表
DESCRIBE pet;
# 查看表
LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;
# 将txt文件导入数据表
LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet
LINES TERMINATED BY '\r\n'; # 指定行分隔符
INSERT INTO pet
VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL); # 插入一行
SELECT * FROM pet;
SELECT * FROM pet WHERE species = 'snake' OR species = 'bird';
SELECT name, birth FROM pet;
SELECT name, birth FROM pet ORDER BY birth DESC;
计算生日和现在的年龄
SELECT name, birth, CURDATE(),
TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
FROM pet;
查看指定月份
SELECT name, birth FROM pet WHERE MONTH(birth) = 5;
和null
运行的结果都是null
SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;
0和空字符串不是null
SELECT 0 IS NULL, 0 IS NOT NULL, '' IS NULL, '' IS NOT NULL;
1.like
SELECT * FROM pet WHERE name LIKE 'b%';
以b开头的名字
SELECT * FROM pet WHERE name LIKE '%fy';
以fy结尾的
SELECT * FROM pet WHERE name LIKE '%w%';
包含w的
SELECT * FROM pet WHERE name LIKE '_____';
姓名长度为5的 一个_
代表一个字符
2.REGEXP_LIKE()
SELECT * FROM pet WHERE REGEXP_LIKE(name, '^b');
以b开头的
SELECT * FROM pet WHERE REGEXP_LIKE(name, 'fy$');
以fy结尾的
SELECT * FROM pet WHERE REGEXP_LIKE(name, 'w');
包含w的
SELECT * FROM pet WHERE REGEXP_LIKE(name, '^.....$');
长度为5的
SELECT owner, COUNT(*) FROM pet GROUP BY owner;
SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species
FROM pet AS p1 INNER JOIN pet AS p2
ON p1.species = p2.species
AND p1.sex = 'f' AND p1.death IS NULL
AND p2.sex = 'm' AND p2.death IS NULL;
直接将sql命令写在文本里
mysql < batch-file > mysql.out