---
title: "mysql常用命令"
author: "Even521"
date: "2014-11-04T16:03:16Z"
tags: []
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2014-11-04T16:03:16Z"
id: 2152307
url: "https://even521.iteye.com/blog/2152307"
---

1.产看服务器内的数据库：

show databases；

2.删除test数据库：

drop database test；

show databases；

3.创建mytest数据库：

create database mytest；

注意：windows与Linux中数据库名与表名的处理是不同的。在windows环境下是不区分大小写的，但是在Linux中是区分的。如table与Table在windows下是同一张表，而在Linux中是两个完全不同的表。为了不至于在不同的环境中产生歧义，所有的数据库名，表明，列明全采用小写字符。

4.创建数据库的专用用户：

创建一个新用户uesr 并且对用户赋予权限：

grant all privileges on mytest.\*to  [user@localhost](mailto:user@localhost) identified by "123456"

（all privileges：一次性赋予所有的权限  select 检索、update 更新、delete 删除 、create 创建等等 ）

5.显示现在使用的数据库：

select database（）；

6.创建新表 customer：

create table customer（mid CHAR(5) primary key,name varchar(20),birth data,sex char(1) default '0'）;

7.创建表时指定字符集 utf-8：

create table customer（mid CHAR(5) primary key,name varchar(20),birth data,sex char(1) default '0'）charset=utf-8;

8.显示user用户下所有表：

show tables；

9.显示cutomer表结构：

desc customer；

10.删除表：

drop table cutomer；

11.插入数据：

insert into customer values（‘N001’，‘小花’，‘1991-11-11’，1）

12.查看表数据：

select * from customer；

13.Auto\_INCREMENT 自增序列：

AUTO\_INCTEMENT用于定义自动增数据列。在MySql中定义自增序列时有三个表要条件。

(1)数据必须为int、tinyint、smallint等整数类型。

(2)定义后附加AUTO\_INCTEMENT关键字，表示此列为自增序列。

(3)使用PRIMARY KEY等设置其唯一性。

14.初始化AUTO\_INCRENMENT

alter table customer AUTO\_INCREMENT=0；

15.导入数据库Mytest

-u root -p Mytest &lt;　sampledb.sql

 

16.模糊查询：

select name from customer where name like ‘li%’；

17.NULL条件：

select name，birth from customer where birth=null；（错误）

select name，birth from customer where birth is null；

18.多个条件表达式的组合（查询性别为女性并且生日非空的数据）：

select name，birth，sex from customer where sex=‘1’and birth is not null；

19.使用括号优先级（查询1991年以前和2000年一会后的女生数据）：

select name，birth，sex from customer where（birth&lt;='1991-01-01' or birth&gt;='2000'） and sex='1';

20.结果排序（按照性别升序，且生日降序排列）：

select * from customer oreder by sex ASC，birth desc；

21.取得指定件数间（m到n之间）的记录（从列表中取出生日最年轻以及第二年轻的成员记录）：

select * from customer order by birth desc limit 2；

（原则上limit 语句要与order by同时使用，如果没有指定排序方式，数据库就会随机的顺序抽取出，这事可能会得到的结果不同）

22.数据分组：

select sex，count（mid） from customer group by sex；

23.列的别名：

select sex，count（mid） as cnt from customer group by sex；

注意：count函数并不是单纯地统计件数，而是统计非NULL记录的，birth中有NULL，因此count（birth）数据有变化。所以在用count时候最好选择不含有null值的列，或者就使用特别的count（\*）