Mysql使用大全-从基础到存储过程_MySQL
bitsCN.com
看到院子里总结的Mysql用法,我觉得没有我的全面,我的从登录到高级的存储过程都涉及到,这部分是我平常不会或是出现问题都会拿来看,不过现在就和我一起来使用命令模式学习一下数据库最基本的吧,平常习惯了phpmyadmin等其他工具的的朋友有的根本就不会命令,如果让你笔试去面试我看你怎么办,所以,学习一下还是非常有用的,也可以知道你通过GUI工具的时候工具到底做了什么。Mysql用处很广,是php最佳拍档,Java中使用也很方便。
我是通过Windows 7 操作的,所以打开运行-输入cmd吧,然后输入mysql -hlocalhost -uroot -p;回车后就可以输入密码了,这里可以*号显示,当然也可以和-p连写的,这就是登录mysql。修改密码mysqladmin -uroot -pold password new;这里的root是用户名 new是你的新密码。退出是什么命令,曾有人问我,我说你直接点X好了,不过命令是quit;退出到cmd环境,退出cmd环境命令是exit;接着就是操作mysql的增删改查,常称为CURD操作。
#登录数据库mysql -hlocalhost -uroot -p;#修改密码mysqladmin -uroot -pold password new;#显示数据库show databases;#显示数据表show tables;#选择数据库use examples;#创建数据库并设置编码utf-8 多语言create database `examples` default character set utf8 collate utf8_general_ci;#删除数据库drop database examples;#创建表create table test( id int(10) unsigned zerofill not null auto_increment, email varchar(40) not null, ip varchar(15) not null, state int(10) not null default '-1', primary key (id))engine=InnoDB;#显示表结构describe #删除表drop table test;#重命名表alter table test_old rename test_new;#添加列alter table test add cn int(4) not null;#修改列alter table test change id id1 varchar(10) not null;#删除列 alter table test drop cn;#创建索引alter table test add index (cn,id);#删除索引alter table test drop index cn#插入数据insert into test (id,email,ip,state) values(2,'qq@qq.com','127.0.0.1','0');#删除数据 delete from test where id = 1;#修改数据update test set id='1',email='q@qq.com' where id=1;#查数据select * from test; #取所有数据select * from test limit 0,2; #取前两条数据 select * from test email like '%qq%' #查含有qq字符 _表示一个 %表示多个select * from test order by id asc;#降序descselect * from test id not in('2','3');#id不含2,3或者去掉not表示含有select * from test timer between 1 and 10;#数据在1,10之间#---------------------------表连接知识------------------------------#等值连接又叫内链接 inner join 只返回两个表中连接字段相等的行select * from A inner join B on A.id = B.id; #写法1select * from A,B where A.id = B.id; #写法2select a.id,a.title from A a inner join B b on a.id=b.id and a.id=1;#写法3 表的临时名称select a.id as ID,a.title as 标题 from A inner join B on A.id=B.id;#添加as字句#左连接又叫外连接 left join 返回左表中所有记录和右表中连接字段相等的记录select * from A left join B on A.id = B.id;select * from A left join (B,C,D) on (B.i1=A.i1 and C.i2=A.i2 and D.i3 = A.i3);#复杂连接#右连接又叫外连接 right join 返回右表中所有记录和左表中连接字段相等的记录select * from A right join B on A.id = B.id;#完整外部链接 full join 返回左右表中所有数据select * from A full join B on A.id = B.id;#交叉连接 没有where字句 返回卡迪尔积select * from A cross join B;-------------------------表连接结束-----------------------------------------------------------------------------索引创建------------------------------------------------show index from A #查看索引alter table A add primary key(id) #主键索引alter table A add unique(name) #唯一索引alter table A add index name(name) #普通索引alter table A add fulltext(name) #全文索引alter table A add index name(id,name) #多列索引#常用函数abs(-1)#绝对值pi()#pi值sqrt(2)#平方根mod(-5,3)#取余-2ceil(10.6)#进位+1 结果11 ceil(10.0)结果10floor(10.6)#取整 10round(2.5)#四舍五入到整数 结果3round(2.5,2)#保留两位小数 结果2.50truncate(2.5234,3)#取小数后3位不四舍五入 2.523sign(-2);#符号函数 返回-1 0还是0 正数返回1pow(2,3),exp(2);#2的3次幂 或e的2次幂log(2),log10(2);#求对数radians(180),degrees(0.618);#角度弧度转换sin(0.5),asin(0.5)#正弦和反正弦 类似cos acos tan atanlength('hi')#计算字符长度concat('1',1,'hi')#合并字符串insert('12345',1,0,'7890');#从开头第1个字符开始到0个结束,替换成后边字符串,0表示在最前边插入ucase('a'),lcase('A')#转成大写和小写left('abcd',2),right('abcd',2);#返回前两个字符和后两个字符ltrim(' 0 '),rtrim(' 0 '),trim(' 0 ')#删除空格replace('1234567890','345678','0');#替换输出12090substring('12345',1,2)#取字符 输出12 1是位置 2是长度instr('1234','234');#取得234位置是2reverse('1234');#反序输出4321current()#返回日期curtime()#返回时间now()#返回日期时间month(now())#当前月份 monthname 英文月份dayname(now())#星期英文 dayofweek()1是星期天 weekday()1是星期二week(now())#本年第多少周dayofyear(now()),dayofmonth(now())#今天是本年第多少天 今天是本月第多少天year(now()),month(now()),day(now()),hour(now()),minute(now()),second(now())#返回年月日 时分秒time_to_sec(now()),sec_to_time(3600*8);#转换时间为秒和还原version()#mysql版本database()#当前连接的数据库 没有为nulluser()#获取用户名md5('a')#加密字符串ascii('a')#ascii值97bin(100),hex(100),oct(100)#返回二进制 十六进制 八进制conv(10001,2,8);#各种进制相互转换rand()#生成0到1之间随机数sleep(0.02)#暂停秒数数据库优化1.开启缓存,尽量使用php函数而不是mysql2. explain select 语句可以知道性能3.一行数据使用 limit 1;4.为搜索字段重建索引 比如关键字 标签5.表连接join保证字段类型相同并且有其索引6.随机查询使用php $r = mysql_query("SELECT count(*) FROM user"); $d = mysql_fetch_row($r); $rand = mt_rand(0,$d[0] - 1); $r = mysql_query("SELECT username FROM user LIMIT $rand, 1");7.避免使用select * 应该使用具体字段8.每张表都是用id主键,并且是unsigned int9.对于取值有限而固定使用enum类型,如性别 国家 名族 部门 状态10.尽可能使用not null ip存储使用int(4),使用ip 转化函数ip2long()相互long2ip()11.delete和insert语句会锁表,所以可以采用分拆语句操作 while(1){操作语句;usleep(2000);}12.选择正确的存储引擎;MyISAM适合大量查询 写操作多用InnoDB支持事务#存储过程#存储程序delimiter #定义存储程序create procedure getversion(out params varchar(20)) #params是传出参数 in传进 out传出 inout传回beginselect version() into params; #版本信息赋值paramsendcall getversion(@a); #调用存储过程select @a;delimiter #定义存储函数create function display(w varchar(20)) returns varchar(20)beginreturn concat('hello',w);endselect display('world');drop procedure if exists spName; #删除一个存储过程alter function spName [];#修改一个存储过程show create procedure spName;#显示存储过程信息declare varName type default value;#声明局部变量#if语句if 条件 then 语句elseif 条件 then 语句else 语句end if#case语句case 条件when 条件 then 语句when 条件 then 语句else 语句end case#loop语句fn:loop语句end loop fn;leave fn #退出循环#while语句fn:while 条件 do语句end while fn#mysql使用帮助资料? contents; #列出帮助类型? data types;#列出数据类型? int;#列出具体类型? show;#show语句? create table;##常见表的比较 Myisam BDB Memory InnoDB Archive存储限制 no no yes 64T no事物安全 支持 支持 锁机制 表锁 页锁 表锁 行锁 行锁全文索引 支持外键支持 支持myisam frm存储表定义 MYD存储数据 MYI存储索引InnoDB 用于事务处理char 和 varchar保存和索引都不相同浮点数float(10,2) 定点数decimal(10,2)长度一定下,浮点数表示更大数据范围,缺点是引起精度丢失,货币等使用定点数存储 索引适合于where字句或者连接字句列 对于唯一值使用唯一索引添加新用户 grant select,insert,update,delete on *.* to Yoby@localhost identified by 'mysql'; # *.* 数据库名.表名,限制登录某一个数据库 test.* localhost是本地主机 网络可以使用 '%'代替所有主机 'mysql'是密码 Yoby是用户名 所有权限可以用 all代替查看用户权限 show grants for 'root'@'localhost';移除权限 revoke all on *.* from root@localhost;group by id 分组having 限制字句select1 union select2 联合查询有重复去掉保留一行select2 union all select2 所有行合并到结果集中去
这是一份最完整的mysql笔记,需要的可以复制保存了!
(原创 Yoby)
bitsCN.com
Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This website reported on March 7 that Dr. Zhou Yuefeng, President of Huawei's Data Storage Product Line, recently attended the MWC2024 conference and specifically demonstrated the new generation OceanStorArctic magnetoelectric storage solution designed for warm data (WarmData) and cold data (ColdData). Zhou Yuefeng, President of Huawei's data storage product line, released a series of innovative solutions. Image source: Huawei's official press release attached to this site is as follows: The cost of this solution is 20% lower than that of magnetic tape, and its power consumption is 90% lower than that of hard disks. According to foreign technology media blocksandfiles, a Huawei spokesperson also revealed information about the magnetoelectric storage solution: Huawei's magnetoelectronic disk (MED) is a major innovation in magnetic storage media. First generation ME

Vue3+TS+Vite development tips: How to encrypt and store data. With the rapid development of Internet technology, data security and privacy protection are becoming more and more important. In the Vue3+TS+Vite development environment, how to encrypt and store data is a problem that every developer needs to face. This article will introduce some common data encryption and storage techniques to help developers improve application security and user experience. 1. Data Encryption Front-end Data Encryption Front-end encryption is an important part of protecting data security. Commonly used

What is cache? A cache (pronounced ka·shay) is a specialized, high-speed hardware or software component used to store frequently requested data and instructions, which in turn can be used to load websites, applications, services, and other aspects of the system faster part. Caching makes the most frequently accessed data readily available. Cache files are not the same as cache memory. Cache files refer to frequently needed files such as PNGs, icons, logos, shaders, etc., which may be required by multiple programs. These files are stored in your physical drive space and are usually hidden. Cache memory, on the other hand, is a type of memory that is faster than main memory and/or RAM. It greatly reduces data access time since it is closer to the CPU and faster compared to RAM

Git is a fast, reliable, and adaptable distributed version control system. It is designed to support distributed, non-linear workflows, making it ideal for software development teams of all sizes. Each Git working directory is an independent repository with a complete history of all changes and the ability to track versions even without network access or a central server. GitHub is a Git repository hosted on the cloud that provides all the features of distributed revision control. GitHub is a Git repository hosted on the cloud. Unlike Git which is a CLI tool, GitHub has a web-based graphical user interface. It is used for version control, which involves collaborating with other developers and tracking changes to scripts and

How to correctly use sessionStorage to store sensitive information requires specific code examples. Whether in web development or mobile application development, we often need to store and process sensitive information, such as user login credentials, ID numbers, etc. In front-end development, using sessionStorage is a common storage solution. However, since sessionStorage is browser-based storage, some security issues need to be paid attention to to ensure that the stored sensitive information is not maliciously accessed and used.

How do PHP and swoole achieve efficient data caching and storage? Overview: In web application development, data caching and storage are a very important part. PHP and swoole provide an efficient method to cache and store data. This article will introduce how to use PHP and swoole to achieve efficient data caching and storage, and give corresponding code examples. 1. Introduction to swoole: swoole is a high-performance asynchronous network communication engine developed for PHP language. It can

This article is reprinted from the WeChat public account "Living in the Information Age". The author lives in the information age. To reprint this article, please contact the Living in the Information Age public account. For students who are familiar with database operations, writing beautiful SQL statements and finding ways to find the data they need from the database is a routine operation. For students who are familiar with machine learning, it is also a routine operation to obtain data, preprocess the data, build a model, determine the training set and test set, and use the trained model to make a series of predictions about the future. So, can we combine the two technologies? We see that data is stored in the database, and predictions need to be based on past data. If we query future data through the existing data in the database, then it is

Methods and techniques for using PHP arrays to implement data caching and storage. With the development of the Internet and the rapid growth of data volume, data caching and storage have become one of the issues that we must consider during the development process. As a widely used programming language, PHP also provides a wealth of methods and techniques to implement data caching and storage. Among them, using PHP arrays for data caching and storage is a simple and efficient method. 1. Data caching The purpose of data caching is to reduce the number of accesses to the database or other external data sources, thereby improving
