MySql速查-1-数据库基本操作
程序员文章站
2022-05-17 07:59:52
...
MySql is RDBMS(Relational Database Management System) 创建连接mysql的用户 % mysql -p -u root mysql CREATE USER 'sampadm'@'localhost' IDENTIFIED BY 'secret'; mysql GRANT ALL ON sampdb.* TO 'sampadm'@'localhost' 连接mysql mysql -h host_nam
MySql is RDBMS(Relational Database Management System)
创建连接mysql的用户
% mysql -p -u root
mysql> CREATE USER 'sampadm'@'localhost' IDENTIFIED BY 'secret';
mysql> GRANT ALL ON sampdb.* TO 'sampadm'@'localhost'
连接mysql
mysql -h host_name -p -u user_name
退出mysql
mysql> quit
执行mysql
mysql> Select Now(),User(),Version();
mysql> Select Now(),User(),Version()\g // ; \g 终止语句
mysql> Select Now(),User(),Version()\G //竖排显示,每行一个值
脚本执行
% mysql % mysql sampdb 创建数据表
mysql> CREATE TABLE member
(
member_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (member_id),
first name VARCHAR(20) NOT NULL,
last name VARCHAR(20) NOT NULL,
suffix VARCHAR(5) NOT NULL,
expiration DATE NULL
);
查看表结构
mysql> DESCRIBE member;
显示特定列
mysql> SHOW COLUMNS FROM member LIKE '%name';
列出表
mysql> SHOW TABLES;
% mysqlshow sampdb
列出数据库
mysql> SHOW DATABASE;
% mysql show
插入数据行
mysql> CREATE TABLE student
(
name VARCHAR(20) NOT NULL,
sex ENUM('F','M') NOT NULL,
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (student_id)
)ENGINE = InnoDB
mysql> INSERT INTO student VALUES('Alex','M',NULL);
mysql> INSERT INTO student VALUES('Alex','M',NULL),('Bob','F',NULL); //括号内包含所有列
mysql> INSERT INTO student (name,sex) VALUES('Alex','M');
加载数据文件
mysql> LOAD DATA LOCAL INFILE 'member.txt' INTO TABLE member;
% mysqlimport --local samdb member.txt
检索信息
书定顺序,Select--From--Where--Group by--Having--Order by
执行顺序,From--Where--Group by--Having--Select--Order by
NULL值表示'无数据',不能与'有数据'的值比较
LIMIT number,限制显示行
日期函数,YEAR(),MONTH(),DAYOFMONTH()
变量,@variable
mysql> SELECT @birth:=birth FROM student where name='Bob';
mysql> SELECT name FROM student WHERE birth mysql> SET @today=CURDATE();
mysql> SET @one_week_ago:=DATE_SUB(@today,INTERVAL 7 DAY);
统计信息
DISTINCT,清除重复信息
COUNT(*),计数所有行
COUNT(数据列),非NULL行
mysql> SELECT state,COUNT(*) FROM president GROUP BY status ORDER BY count DESC LIMIT 4;
多表联结
left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录
right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录
inner join(等值连接) 只返回两个表中联结字段相等的行
exists 与 in 最大的区别在于 in引导的子句只能返回一个字段,比如:
select name from student where sex = 'm' and mark in (select 1,2,3 from grade where ...),
in子句返回了三个字段,这是不正确的,exists子句是允许的,但in只允许有一个字段返回,在1,2,3中随便去了两个字段即可
删除数据行
DELETE FROM tbl_name WHERE which rows to delete;
更新数据行
UPDATE tbl_name SET which columns to change WHERE which rows to update;
简化链接过程
1. ~/.my.cnf
[client]
host=server_host
user=your_name
password=your_pass
2. 命令历史
% !my //最近使用过的命令
3. alias sampdb 'mysql -h host_name -p -u sampadm sampdb'
聚合函数,MIN(),MAX(),SUN(),AVG()
创建数据库
CREATE DATABASE [IF NOT EXISTS] db_name [CHARACTER SET charset][COLLATE collation];
删除数据库
DROP DATABASE db_name;
变更数据库
ALTER DATABASE [db_name][CHARACTER SET charset][COLLATE collation];