返回顶部
首页 > 资讯 > 数据库 >Learning MySQL and MariaDB
  • 574
分享到

Learning MySQL and MariaDB

2024-04-02 19:04:59 574人浏览 八月长安
摘要

PART II Database Structures To start, let ’s create a database that will contain infORM

PART II

Database Structures

To start, let ’s create a database that will contain infORMation about birds and call it rookery . To do this, enter the following from within the Mysql client:

CREATE DATABASE rookery;

 

DROP DATABASE rookery ;

CREATE DATABASE rookery

CHARACTER SET latin1

COLLATE latin1_bin ;

 

Now that we ’ve created a database, let’s confirm that it’s there, on the MySQL Server. To get a list of databases, enter the following sql statement:

SHOW DATABASES;

+--------------------+

| Database |

+--------------------+

| information_schema |

| rookery |

| mysql |

| test |

+--------------------+

three other databases that were created when MySQL was installed on the server.

 

Before beginning to add tables to the rookery database, enter the following command

into the mysql client:

USE rookery

 

CREATE TABLE birds (

bird_id INT AUTO_INCREMENT PRIMARY KEY ,

scientific_name VARCHAR ( 255 ) UNIQUE ,

common_name VARCHAR ( 50 ),

family_id INT ,

description TEXT );

 

The AUTO_INCREMENT option tells MySQL to automatically increment the value of this

field. It will start with the number 1, unless we specify a different number.

 

 

DESCRIBE birds;

+-----------------+--------------+------+-----+---------+----------------+

| Field | Type | Null | Key | Default | Extra |

+-----------------+--------------+------+-----+---------+----------------+

| bird_id | int(11) | NO | PRI | NULL | auto_increment |

| scientific_name | varchar(255) | YES | UNI | NULL | |

| common_name | varchar(50) | YES | | NULL | |

| family_id | int(11) | YES | | NULL | |

| description | text | YES | | NULL | |

+-----------------+--------------+------+-----+---------+----------------+

 

Inserting Data

INSERT INTO birds ( scientific_name , common_name )

VALUES ( 'Charadrius vociferus' , 'Killdeer' ),

( 'Gavia immer' , 'Great Northern Loon' ),

( 'Aix sponsa' , 'Wood Duck' ),

( 'Chordeiles minor' , 'Common Nighthawk' ),

( 'Sitta carolinensis' , ' White-breasted Nuthatch' ),

( 'Apteryx mantelli' , 'North Island Brown Kiwi' );

 

SELECT * FROM birds;

+---------+----------------------+-------------------+-----------+-------------+

| bird_id | scientific_name | common_name | family_id | description |

+---------+----------------------+-------------------+-----------+-------------+

| 1 | Charadrius vociferus | Killdeer | NULL | NULL |

| 2 | Gavia immer | Great Northern... | NULL | NULL |

| 3 | Aix sponsa | Wood Duck | NULL | NULL |

| 4 | Chordeiles minor | Common Nighthawk | NULL | NULL |

| 5 | Sitta carolinensis | White-breasted... | NULL | NULL |

| 6 | Apteryx mantelli | North Island... | NULL | NULL |

+---------+----------------------+-------------------+-----------+-------------+

 

More Perspectives on Tables

 

SHOW CREATE TABLE birds \G

 

Table: birds

Create Table: CREATE TABLE `birds` (

`bird_id` int(11) NOT NULL AUTO_INCREMENT,

`scientific_name` varchar(255) COLLATE latin1_bin DEFAULT NULL,

`common_name` varchar(50) COLLATE latin1_bin DEFAULT NULL,

`family_id` int(11) DEFAULT NULL,

52 | Chapter 4: Creating Databases and Tables

`description` text COLLATE latin1_bin,

PRIMARY KEY (`bird_id`),

UNIQUE KEY `scientific_name` (`scientific_name`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_bin

 

CHAPTER 5

Altering Tables

use the mysqldump utility to make a backup of the tables you ’re altering or the whole database.

备份表

mysqldump -- user = ' russell ' - p \

rookery birds > / tmp / birds . sql

备份数据库

mysqldump -- user = ' russell ' - p \

rookery > rookery . sql

 

恢复:

Later on, if you have a problem and need to restore the database back to where you were at the end of a chapter, you would enter something like the following from the command line:

mysql -- user = ' russell ' - p \

rookery < rookery - ch3 - end . sql

 

The basic syntax for the ALTER TABLE is simple:

ALTER TABLE table_name changes;

 

ALTER TABLE bird_families ADD COLUMN order_id INT ;

 

To make a copy of the birds table, we ’ ll use the CREATE TABLE statement with the LIKE clause. This was covered in Chapter 4) In fact, let ’ s create the new table in the test database just to work separately on it (this isn ’ t necessary, but it ’ s a Good practice to have a development database separate from the live one. To do this, enter the following in mysql on your server:

 

CREATE TABLE test.birds_new LIKE birds;

 

This DESCRIBE statement will show you the structure of the new table. Because we copied only the structure of the birds table when we created the new table, there is no data in this table. To do that, we could use an INSERT statement coupled with a SELECT like so:

INSERT INTO birds_new

SELECT * FROM rookery.birds;

This will work fine. However, there ’ s another method that creates a table based on another table and copies over the data in the process:

CREATE TABLE birds_new_alternative

SELECT * FROM rookery.birds;

This will create the table birds_new_alternative with the data stored in it. However,

if you execute a DESCRIBE statement for the table, you will see that it did not set the bird_id column to a PRIMARY KEY and did not set it to AUTO_INCREMENT . So in our

situation, the first method we used to create the table is preferred, followed by an INSERT INTO...SELECT statement. Enter the following to delete the alternative table:

DROP TABLE birds_new_alternative;

 

ALTER TABLE birds_new DROP COLUMN wing_id ;

 

There ’s no UNDO statement in MySQL

 

ALTER TABLE birds_new ADD COLUMN wing_id CHAR ( 2 ) AFTER family_id ;

This will put the wing_id column after the family_id in the table. Run the DESCRIBE

statement again to see for yourself. By the way, to add a column to the first position, you would use the keyWord FIRST instead of AFTER . FIRST takes no column name.

 

ALTER TABLE birds_new

ADD COLUMN body_id CHAR ( 2 ) AFTER wing_id ,

ADD COLUMN bill_id CHAR ( 2 ) AFTER body_id ,

ADD COLUMN endangered BIT DEFAULT b '1' AFTER bill_id ,

CHANGE COLUMN common_name common_name VARCHAR ( 255 );

 

ALTER TABLE birds_new

ADD COLUMN body_id CHAR ( 2 ) AFTER wing_id ,

ADD COLUMN bill_id CHAR ( 2 ) AFTER body_id ,

ADD COLUMN endangered BIT DEFAULT b '1' AFTER bill_id ,

CHANGE COLUMN common_name common_name VARCHAR ( 255 );

 

In one of the columns added here, the endangered column, we ’re using a data type we haven ’t used yet in this book: BIT . This stores one bit, which takes a values of either set or unset —basically, 1 or 0.

 

UPDATE birds_new SET endangered = 0 WHERE bird_id IN ( 1 , 2 , 4 , 5 );

 

SELECT bird_id, scientific_name, common_name

FROM birds_new

WHERE endangered \G

*************************** 1. row ***************************

bird_id: 3

scientific_name: Aix sponsa

common_name: Wood Duck

Notice that in the WHERE clause of the SELECT statement we are selecting rows where the endangered column has a value. For the column data type of BIT , this is all that ’s needed , and it has the same effect as if we specified WHERE endangered = 1 . To filter on the reverse —to select rows in which the bit for the endangered column is not set —use the NOT operator like so:

SELECT * FROM birds_new WHERE NOT endangered \ G

 

如果希望endangered可以存0和1以为的值, 下面语句修改endangered 列成枚举类型 。

ALTER TABLE birds_new MODIFY COLUMN endangered

ENUM ( 'Extinct' ,

'Extinct in Wild' ,

'Threatened - Critically Endangered' ,

'Threatened - Endangered' ,

'Threatened - Vulnerable' ,

'Lower Risk - Conservation Dependent' ,

'Lower Risk - Near Threatened' ,

'Lower Risk - Least Concern' )

AFTER family_id ;

 

Let ’s run the SHOW COLUMNS statement with the LIKE clause to see just the column settings for the endangered column:

SHOW COLUMNS FROM birds_new LIKE 'endangered' \G

*************************** 1. row ***************************

Field: endangered

Type: enum('Extinct','Extinct in Wild',

'Threatened - Critically Endangered',

'Threatened - Endangered',

'Threatened - Vulnerable',

'Lower Risk - Conservation Dependent',

'Lower Risk - Near Threatened',

'Lower Risk - Least Concern')

Null: YES

Key:

Default: NULL

Extra:

 

Dynamic Columns

This is something that is available only in MariaDB, as of version 5.3. It ’s similar

to an ENUM column

。。。

Renaming a Table

RENAME TABLE rookery . birds TO rookery . birds_old , test . birds_new TO rookery . birds ;

If there was a problem in doing any of these changes, an error message would be generated

and none of the changes would be made. If all of it went well, though, we should

have two tables in the rookery database that are designed to hold data on birds.

Let ’s run the SHOW TABLES statement to see the tables in the rookery database. We ’ll

request only tables starting with the word birds by using the LIKE clause with the wildcard,

% . Enter the following in mysql :

SHOW TABLES IN rookery LIKE 'birds%';

 

 

 

PART III

Basics of Handling Data

CHAPTER 6

Inserting Data

The INSERT statement adds rows of data into a table. It can add a single row or multiple rows at a time. The basic syntax of this SQL statement is:

INSERT INTO table [( column , …)]

VALUES ( value , …), (…), …;

Replacing Data

REPLACE INTO bird_families

( scientific_name , brief_description , order_id )

VALUES ( 'Viduidae' , 'Indigobirds & Whydahs' , 128 ),

( 'Estrildidae' , 'Waxbills, Weaver Finches, & Allies' , 128 ),

( 'Ploceidae' , 'Weavers, Malimbe, & Bishops' , 128 );

Query OK , 6 rows affected ( . 39 sec )

Records : 3 Duplicates : 3 Warnings :

Actually, when a row is replaced using the REPLACE statement, it ’s first deleted completely and the new row is then inserted.

 

 

CHAPTER 7

Selecting Data

Limiting Results

SELECT common_name, scientific_name, family_id

FROM birds

WHERE family_id IN(103, 160, 162, 164)

AND common_name != ''

ORDER BY common_name

LIMIT 3, 2;

+------------------------+-------------------------+-----------+

| common_name | scientific_name | family_id |

+------------------------+-------------------------+-----------+

| American Avocet | Recurvirostra americana | 162 |

| American Golden-Plover | Pluvialis dominica | 103 |

+------------------------+-------------------------+-----------+

This LIMIT clause has two values: the point where we want the results to begin, then the number of rows to display. The result is to show rows 3 and 4. Incidentally, LIMIT 3 used previously is the same as LIMIT 0, 3 : the 0 tells MySQL not to skip any rows.

 

SELECT orders.scientific_name AS 'Order',

families.scientific_name AS 'Family',

COUNT(*) AS 'Number of Birds'

FROM birds, bird_families AS families, bird_orders AS orders

WHERE birds.family_id = families.family_id

AND families.order_id = orders.order_id

AND orders.scientific_name = 'Pelecaniformes'

GROUP BY Family;

+----------------+-------------------+-----------------+

| Order | Family | Number of Birds |

+----------------+-------------------+-----------------+

| Pelecaniformes | Ardeidae | 157 |

| Pelecaniformes | Balaenicipitidae | 1 |

| Pelecaniformes | Pelecanidae | 10 |

| Pelecaniformes | Scopidae | 3 |

| Pelecaniformes | Threskiornithidae | 53 |

+----------------+-------------------+-----------------+

We gave the GROUP BY clause the Family alias, which is the scientific_name column

from the bird_families table. MySQL returns one results set for all five families, for one SELECT statement.

 

CHAPTER 8

Updating and Deleting Data

Updating Multiple Tables

UPDATE prize_winners , humans

SET winner_date = NULL ,

prize_chosen = NULL ,

prize_sent = NULL

WHERE country_id = 'uk'

AND prize_winners . human_id = humans . human_id ;

This SQL statement checks rows in one table, associates those rows to the related rows in another table, and changes those rows in that second table. Notice that we listed the two tables involved in a comma-separated list. We then used the SET clause to set the values of the columns related to winning a prize to NULL. In the WHERE clause, we give the condition that the country_id

Deleting Data

There is no UNDELETE or UNDO statement for restoring rows that you delete.

Deleting in Multiple Tables

There are many situations where data in one table is dependent on data in another table.If you use DELETE to delete a row in one table on which a row in another table is dependent,you ’ll have orphaned data. You could execute another DELETE to remove that other row, but it ’s usually better to delete rows in both tables in the same DELETE statement,especially when there may be many rows of data to delete.

The syntax for the DELETE that deletes rows in multiple tables is:

DELETE FROM table [, table ]

USING table [, . . . ]

[WHERE condition ];

 

DELETE FROM humans , prize_winners

USING humans JOIN prize_winners

WHERE name_first = 'Elena'

AND name_last = 'Bokova'

AND email_address LIKE '%yahoo.com'

AND humans . human_id = prize_winners . human_id ;

 

 

 

 

CHAPTER 9

Joining and Subquerying Data

Joining Tables

SELECT book_id , title , status_name

FROM books JOIN status_names

WHERE status = status_id ;

 

 

PART IV

Built-In Functions

 

 

 

PART V

Administration and Beyond

 

CHAPTER 13

User Accounts and Privileges

GRANT ALL ON rookery.*

TO 'lena_stankoska'@'localhost';

SHOW GRANTS FOR 'lena_stankoska'@'localhost';

+---------------------------------------------------------------------+

| Grants for lena_stankoska@localhost |

+---------------------------------------------------------------------+

| GRANT USAGE ON *.* TO 'lena_stankoska'@'localhost' |

| GRANT ALL PRIVILEGES ON `rookery`.* TO 'lena_stankoska'@'localhost' |

+---------------------------------------------------------------------+

 

When we executed

the CREATE USER statement and didn ’t specify a host, we created one user account—one with the wildcard for the host.

When we executed the GRANT statement to give privileges

to the same user, but with the host of localhost, a second user account was created.

 

SELECT User, Host

FROM mysql.user

WHERE User LIKE 'lena_stankoska';

+----------------+-----------+

| User | Host |

+----------------+-----------+

| lena_stankoska | % |

| lena_stankoska | localhost |

+----------------+-----------+

 

To eliminate both of the user accounts that we created for Lena, we will have to execute the DROP USER statement twice, like this:

DROP USER 'lena_stankoska' @ 'localhost' ;

DROP USER 'lena_stankoska' @ '%' ;


您可能感兴趣的文档:

--结束END--

本文标题: Learning MySQL and MariaDB

本文链接: https://lsjlt.com/news/46881.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • Learning MySQL and MariaDB
    PART II Database Structures To start, let ’s create a database that will contain inform...
    99+
    2024-04-02
  • 《深度学习》PDF Deep Learning: Adaptive Computation and Machine Learning series
    《深度学习》PDF Deep Learning: Adaptive Computation and Machine Learning series《深度学习》由全球知名的三位专家Ian Goodfellow、Yoshua Bengio 和A...
    99+
    2023-06-02
  • MariaDB 10.3支持update多表ORDER BY and LIMIT
    MariaDB 10.3支持update多表ORDER BY and LIMIT1)update连表更新,limit语句update t1 join t2 on&nb...
    99+
    2024-04-02
  • MySQL/MariaDB 分区
    查看表的创建命令SHOW CREATE TABLE my_table_name;查看表是否分区(Create_options 字段为 partitioned 或空)SHOW TABLE STATUS LIK...
    99+
    2024-04-02
  • mysql between and、in
    #案例,查询员工员工编号在100到120之间的员工信息 SELECT * FROM employees WHERE employee_id BETWEEN 100 AND 200; #顺序不...
    99+
    2024-04-02
  • mysql import and export
    一、备份数据库:(命令在DOS的mysqlbin目录下执行) mysqldump --opt school>school.bbb 注释:将数据库school备份到school.bbb文件,school.bb...
    99+
    2024-04-02
  • Mysql/Mariadb主从复制
    概念 什么是·Mysql/Mariadb主从复制?     Mysql/Mariadb主从复制:当Master(主)数据库发生变化的时候,变化实时会同步到slave(从)数据库中; 类似于:Samba共享文件(C/S)、NFS网络文件...
    99+
    2021-03-22
    Mysql/Mariadb主从复制
  • mariadb和mysql哪个好
    这篇文章主要介绍了mariadb和mysql哪个好,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。mariadb和mysql哪个好?mariadb...
    99+
    2024-04-02
  • MariaDB下载安装--mysql(win10)
    MySQL环境配置(WINDOWS10) 下载mysql 链接: MariaDB. 首先打开文件资源管理器,右击此电脑,点击属性 选择高级系统设置 点击环境变量,在系统变量中新建MYSQL_HOME并在变量名中添加你自己的mysql地址...
    99+
    2018-02-03
    MariaDB下载安装--mysql(win10)
  • Linux安装MySQL-MariaDB版本
    分享一个安装相比MySQL5.7版本更加简便,更加快速的版本:MariaDB。实验开始前先关闭防火墙:service firewalld stopsetenforce 0之后配置ALI云源:wget -O ...
    99+
    2024-04-02
  • Mysql/MariaDB数据库入门
    内容:1、数据库简介以及mysql/mariadb背景介绍2、数据库的一些名词3、mysql的服务结构4、mysql客户端的使用5、数据类型6、SQL语句介绍7、mysql的事务机制一、数据库简介以及mys...
    99+
    2024-04-02
  • mysql启动报mariadb错误
    当 mysql 启动时出现 mariadb 错误,原因通常是系统中同时安装了 mysql 和 mariadb 且端口相同。解决方法包括:1. 仅安装 mysql;2. 修改 mysql ...
    99+
    2024-08-01
    mysql centos
  • mysql中and的用法
    mysql 中 and 运算符连接布尔表达式,当且仅当所有表达式为真时返回真,否则返回假。它用于缩小查询结果,查找满足多个条件的记录或排除不符合条件的记录。 MySQL 中 AND 的...
    99+
    2024-04-26
    mysql
  • MySQL master and slave have equal MySQL server UUIDs
    今天从一个slave备份出来数据,想再创建一个slave,启动后报错: Last_IO_Error: Fatal error: The slave I/O thread stops b...
    99+
    2024-04-02
  • MySQL/MariaDB读写分离配置
    实现数据库读写分离技术是有很多方法的,在这里我就用一个比较简单的mysql-proxy这个中间件来实现数据库的读写分离; 使用mysql-proxy实现mysql的读写分离,mysql-proxy实际上是作为后端mysql主从服务器的代理...
    99+
    2021-01-12
    MySQL/MariaDB读写分离配置
  • Linux 5月23日 LAMP MYSQL MariaDB
     5月23日任务11.1 LAMP架构介绍11.2 MySQL、MariaDB介绍11.3/11.4/11.5 MySQL安装 LAMP架构介绍从现在开始了...
    99+
    2024-04-02
  • mysql或者mariadb备份脚本
    #!/bin/bash BACK_DIR=/data/mysql_backup HOST=192.168.10.100 USER=node PASSWORD=a12gd DATABASES=(       ...
    99+
    2024-04-02
  • Python3 备份 MySQL/MariaDB(本地+FTP)
    【准备工作】搭建 FTP 服务器:Windows Server 2008 R2 搭建FTP服务如果本机访问报 530 错误:1、检查用户名、密码;2、检查 ftp 目录的用户权限。如果远程主机无法访问,检查...
    99+
    2024-04-02
  • mysql使用mariadb审计插件
    mysql 5.7.12 mariadb  10.1.14 https://mariadb.com/kb/en/mariadb/server_audit-system-variables...
    99+
    2024-04-02
  • MySQL和MariaDB有什么区别
    这期内容当中小编将会给大家带来有关MySQL和MariaDB有什么区别,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。MariaDB数据库管理系统是MySQL的一个分支,主...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作