Mysql官方参考文档:
https://dev.mysql.com/doc/refman/8.0/en/mysql-nutshell.html
查看mysql操作选项: mysql –help
连接mysql服务器:mysql -h host -u user -p
连接本机使用mysql (-h localhost) -u user -p
退出命令: exit quit \q
查看mysql版本和当前日期:select version(),current_date(now());
查看存在数据库:show databases;
访问某数据库:use test;
加用户访问权限:GRANT ALL ON menagerie.* TO 'your_mysql_name'@'your_client_host';
创建数据库:create database newdatabase;
直接连接数据库:mysql -h host -u user -p test; (直接访问test数据库)
查看当前连接数据库:show database();
查看表:show tables;
创建表:CREATE table pet(name VARCHAR(20),owner varchar(20),species VARCHAR(20),sex char(1),birth DATE,death DATE);
查看表结构:describe pet;
添加表数据:
- 新建txt文件,数据存储在文件中,使用load data local infile '/path /pet.txt' into table pet;
(默认使用制表符分隔数据,可以使用\r\n,需要添加(LINES TERMINATED BY '\r\n';))
- 直接添加 insert into pet values('hello','diane','hamster','f','1999-10-14',null);
选择数据: select * from pet;
修改数据:update pet set owner=’Diane’ where name=’hello’;
选择特定的行:select * from pet where name=’hello’;
选择特殊列:select name,owner from pet;
查询排序:select name,birth from pet order by birth;
降序:select name,birth from pet order by birth desc;
升序:select name,birth from pet order by birth asc;
删除表中数据:delete from pet where name='hello';
TRUNCATE TABLE 表名称;(删除表中数据)
删除表:drop table 表名称;
日期计算:SELECT name, birth, CURDATE(),
TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
FROM pet;
模式匹配开头:SELECT * FROM pet WHERE name LIKE 'b%';
结尾:SELECT * FROM pet WHERE name LIKE '%fy';
包含:SELECT * FROM pet WHERE name LIKE '%w%';
字符数量:SELECT * FROM pet WHERE name LIKE '_____';
正则表达式:
计数行:select count(*) from pet;
分组:select 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;
As 给表起别名
Inner join 表进行内连接
常见查询操作:
创建并填充表:
CREATE TABLE shop (
article INT UNSIGNED DEFAULT '0000' NOT NULL,
dealer CHAR(20) DEFAULT '' NOT NULL,
price DECIMAL(16,2) DEFAULT '0.00' NOT NULL,
PRIMARY KEY(article, dealer));
INSERT INTO shop VALUES
(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),
(3,'C',1.69),(3,'D',1.25),(4,'D',19.95);
列的最大值:SELECT MAX(article) AS article FROM shop;
某列最大值的行:SELECT article, dealer, price
FROM shop
WHERE price=(SELECT MAX(price) FROM shop);
每组最大列数:SELECT article, MAX(price) AS price
FROM shop
GROUP BY article
ORDER BY article;