欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

学习SQL:CREATE DATABASE&CREATE TABLE操作

程序员文章站 2022-05-05 12:17:40
...

Welcome to the first article in the Learn SQL series. In this part, we’ll start with two essential commands in SQL: Create Database and Create Table. While both are pretty simple, they should be used first before you start working anything with data (unless you use some template database).

欢迎使用Learn SQL系列中的第一篇文章。 在这一部分中,我们将从SQL中的两个基本命令开始:创建数据库和创建表。 尽管两者都很简单,但是在开始处理数据之前,应首先使用它们(除非使用某些模板数据库)。

Later in this series, I’ll try to cover everything essential for the complete beginner to jump into the magical world of SQL and databases. So, let’s start:

在本系列的后面部分,我将尝试介绍使初学者完全进入SQL和数据库的神奇世界所必需的所有内容。 因此,让我们开始:

学习SQL:CREATE DATABASE&CREATE TABLE操作

The goal of this article is to create a database (using the SQL Create Database command) and two tables (using the SQL Create Table command) as shown in the picture above. In the upcoming articles, we’ll insert data into these tables, update and delete data, but also add new tables and create queries.

本文的目标是创建一个数据库(使用SQL Create Database命令)和两个表(使用SQL Create Table命令),如上图所示。 在接下来的文章中,我们将数据插入这些表中,更新和删除数据,还添加新表并创建查询。

什么是数据库? (What is a database?)

Before we create a database using the SQL Create database command, I want to define what a database is. I’ll use the definition provided by Oracle:

在使用SQL Create database命令创建数据库之前,我想定义一个数据库。 我将使用Oracle提供的定义:

A database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system (DBMS). (source: https://www.oracle.com/database/what-is-database.html)

数据库是通常以电子方式存储在计算机系统中的结构化信息或数据的有组织的集合。 数据库通常由数据库管理系统(DBMS)控制。 (来源: https : //www.oracle.com/database/what-is-database.html

In this article, I’ll use the Microsoft SQL Server Express edition. So, DBMS is SQL Server, and the language we’ll use is T-SQL. Once again I’ll use a quote:

在本文中,我将使用Microsoft SQL Server Express版本。 因此,DBMS是SQL Server,我们将使用的语言是T-SQL。 再次使用引号:

T-SQL (Transact-SQL) is a set of programming extensions from Sybase and Microsoft that add several features to the Structured Query Language (SQL), including transaction control, exception and error handling, row processing and declared variables. (source: https://searchsqlserver.techtarget.com/definition/T-SQL)

T-SQL(Transact-SQL)是Sybase和Microsoft的一组编程扩展,向结构化查询语言(SQL)添加了一些功能,包括事务控制,异常和错误处理,行处理和声明的变量。 (来源: https : //searchsqlserver.techtarget.com/definition/T-SQL

I won’t go in-depth in this article, but we can conclude this part with a statement that a database is an organized set of tables that contain data from the real-world and some additional columns needed for the system to work properly. We’ll discuss these in upcoming articles.

我不会在本文中深入探讨,但是我们可以通过声明数据库是一组有组织的表来结束这一部分,该表包含真实世界中的数据以及系统正常工作所需的一些其他列。 我们将在以后的文章中讨论这些内容。

SQL创建数据库语句 (SQL Create Database statement)

After installing and opening Microsoft SQL Server Management Studio, our screen looks something like this:

安装并打开Microsoft SQL Server Management Studio后 ,我们的屏幕如下所示:

学习SQL:CREATE DATABASE&CREATE TABLE操作

It doesn’t look fun at all. We’ll make it more fun by creating a new database. After clicking on the New Query, the new window opens and we’re able to type something in. It looks like on the picture below:

看起来一点也不有趣。 通过创建一个新数据库,我们将使其更加有趣。 单击“ 新建查询”后 ,将打开新窗口,我们可以输入一些内容。如下图所示:

学习SQL:CREATE DATABASE&CREATE TABLE操作

Before typing anything, we should be sure we’re typing it in the right way. T-SQL is a language and as such it has its’ words – set of rules on how to write different commands.

在键入任何内容之前,我们应该确保以正确的方式键入它。 T-SQL是一种语言,因此它有它的“单词” –有关如何编写不同命令的一组规则。

Luckily, one of these commands is the SQL Create Database command. You can see the full T-SQL Create Database syntax on Microsoft pages.

幸运的是,这些命令之一是SQL Create Database命令。 您可以在Microsoft页面上看到完整的T-SQL创建数据库语法。

I’ll simplify it a lot and go only with the most basic form. In order to create a new database on our server, we need to use the following command:

我将对其进行简化,仅使用最基本的形式。 为了在我们的服务器上创建一个新的数据库,我们需要使用以下命令:

CREATE DATABASE database_name;

Where we’ll use the desired name instead of the database_name.

我们将在其中使用所需名称而不是database_name

SQL创建数据库示例 (SQL Create Database example)

OK, let’s try it. We’ll run a command:

好的,让我们尝试一下。 我们将运行一个命令:

CREATE DATABASE our_first_database;

After running this command, our database is created, and you can see it in the databases list:

运行此命令后,将创建我们的数据库,您可以在数据库列表中看到它:

学习SQL:CREATE DATABASE&CREATE TABLE操作

Click on the + next to the folder Databases, and besides two folders, you’ll also see that our_first_database had been created.

单击文件夹Databases旁边的+,在两个文件夹旁边,您还将看到our_first_database已创建。

This is cool and you’ve just successfully created your first database. The problem is that we don’t have anything stored inside the database. Let’s change that.

这很酷,您已经成功创建了第一个数据库。 问题在于我们数据库中没有存储任何东西。 让我们改变一下。

SQL创建表语句 (SQL Create Table statement)

In database theory, a table is a structure (“basic unit”) used to store data in the database.

在数据库理论中,表是用于在数据库中存储数据的结构(“基本单位”)。

I love to use analogies a lot, so I’ll do it here too. If you think of a library, a database is one shelf with books, and each book is a table. Each book has its own contents but is somehow related to other books on the same shelf – either by sharing some properties, either by just being close.

我很喜欢使用类比,因此我也会在这里做。 如果您想到的是图书馆,那么数据库是一个包含书架的书架,每本书都是一张桌子。 每本书都有其自己的内容,但是与同一架子上的其他书籍有某种联系-通过共享某些属性,或者只是紧密地联系在一起。

There is a lot of theory behind database tables, and how to decide what goes where, but the simplest you can do is following. When we look at our data and we need to decide what goes where we should group data in tables in such a manner that everything that belongs to the same real-life entity goes to the same table.

数据库表背后有很多理论,以及如何决定将数据存放在何处,但是您可以按照的最简单的方法进行。 当我们查看数据时,我们需要决定将表中的数据分组的方式,以使属于同一真实实体的所有内容都进入同一表。

E.g. if we want to store data describing cities and countries, we’ll have two separate tables in our database – one for cities and another one for countries. We won’t mix their data but rather relate them. This goes out of the scope of this article and shall be covered in the upcoming parts of this series.

例如,如果要存储描述城市和国家的数据,我们将在数据库中有两个单独的表–一个用于城市,另一个用于国家。 我们不会混合它们的数据,而是将它们关联起来。 这超出了本文的范围,本系列的后续部分将对此进行介绍。

To define a table, we’ll follow the syntax. You can see full T-SQL Create Table syntax here, but I’ll once more simplify the statement:

要定义表,我们将遵循以下语法。 您可以在此处看到完整的T-SQL Create Table语法 ,但我将再次简化该语句:

CREATE TABLE table_name (
    column_name column_type,
    column_name column_type,
    ...
);

We’ll simply choose the name for our table and list all the columns we want to have in this table. Columns are also called attributes and each column describes a property of one record in the table. The column has its type and we should choose the type based on values we expect in that column (number, text, etc.).

我们只需选择表的名称,然后列出要在该表中包含的所有列。 列也称为属性,每列描述表中一个记录的属性。 该列具有其类型,我们应该根据该列中期望的值(数字,文本等)来选择类型。

SQL创建表示例 (SQL Create Table example)

Let’s take a look at the definition of our two tables:

让我们看一下两个表的定义:

First, we’ll define the city table.

首先,我们将定义城市表。

-- Table: city
CREATE TABLE city (
    id int  NOT NULL IDENTITY(1, 1),
    city_name char(128)  NOT NULL,
    lat decimal(9,6)  NOT NULL,
    long decimal(9,6)  NOT NULL,
    country_id int  NOT NULL,
    CONSTRAINT city_pk PRIMARY KEY  (id)
);

Please notice a few things:

请注意以下几点:

  • NOT NULL -> This is a property telling us that this column can’t be empty (must be defined)

    NOT NULL->这是一个属性,告诉我们此列不能为空(必须定义)
  • IDENTITY(1, 1) -> is also a property of the column telling us that this value shall be generated automatically, starting from 1 and increasing by 1 for each new record

    IDENTITY(1,1)->也是该列的一个属性,告诉我们该值应自动生成,从1开始并为每个新记录增加1
  • CONSTRAINT city_pk PRIMARY KEY (id) -> This is not a column, but the rule, telling us that column id shall contain only UNIQUE values. So only 1 city can have id =5

    CONSTRAINT city_pk主键(id)->这不是一列,而是规则,告诉我们,列ID仅应包含UNIQUE值。 因此只有1个城市的ID = 5
-- Table: country
CREATE TABLE country (
    id int  NOT NULL IDENTITY(1, 1),
    country_name char(128)  NOT NULL,
    country_name_eng char(128)  NOT NULL,
    country_code char(8)  NOT NULL,
    CONSTRAINT country_ak_1 UNIQUE (country_name),
    CONSTRAINT country_ak_2 UNIQUE (country_name_eng),
    CONSTRAINT country_ak_3 UNIQUE (country_code),
    CONSTRAINT country_pk PRIMARY KEY  (id)
);

Here we have 1 new CONSTRAINT and that is the UNIQUE constraining. This one tells us that this value must be UNIQUE within this table. E.g. CONSTRAINT country_ak_1 UNIQUE (country_name) defines that we can’t store 2 countries with the same name.

在这里,我们有1个新的约束,即唯一约束。 这个告诉我们这个值在这个表中必须是UNIQUE。 例如, CONSTRAINT country_ak_1 UNIQUE(国家名定义了我们不能存储两个具有相同名称的国家。

The last part of the script is the definition of foreign keys. We have only 1 such key and it relates city and country table (city.county_id = country.id).

脚本的最后一部分是外键的定义。 我们只有1个这样的键,它与城市和国家/地区表相关联( city.county_id = country.id )。

-- foreign keys
-- Reference: city_country (table: city)
ALTER TABLE city ADD CONSTRAINT city_country
    FOREIGN KEY (country_id)
    REFERENCES country (id);
 

Keys (primary and foreign) are too complex and shall be covered in a separate article. After executing these commands, the status of our database is as in the picture below:

键(主键和外键)太复杂,应在单独的文章中进行介绍。 执行完这些命令后,数据库的状态如下图所示:

学习SQL:CREATE DATABASE&CREATE TABLE操作

结论 (Conclusion)

Congratulations. You have successfully created your first database using SQL Create Database and Create Table commands. We have 2 tables in our database. Now we’re ready to populate them with data and test if we did it as expected. We’ll do it in the next article, so, stay tuned!

恭喜你 您已经使用SQL创建数据库和创建表命令成功创建了第一个数据库。 我们的数据库中有2个表。 现在,我们准备用数据填充它们并测试是否按预期进行。 我们将在下一篇文章中进行介绍,敬请期待!

目录 (Table of contents)

Learn SQL: CREATE DATABASE & CREATE TABLE Operations
Learn SQL: INSERT INTO TABLE
Learn SQL: Primary Key
Learn SQL: Foreign Key
Learn SQL: SELECT statement
Learn SQL: INNER JOIN vs LEFT JOIN
Learn SQL: SQL Scripts
Learn SQL: Types of relations
Learn SQL: Join multiple tables
Learn SQL: Aggregate Functions
Learn SQL: How to Write a Complex SELECT Query
Learn SQL: The INFORMATION_SCHEMA Database
Learn SQL: SQL Data Types
Learn SQL: Set Theory
Learn SQL: User-Defined Functions
Learn SQL: User-Defined Stored Procedures
Learn SQL: SQL Views
Learn SQL: SQL Triggers
Learn SQL: Practice SQL Queries
Learn SQL: SQL Query examples
Learn SQL: Create a report manually using SQL queries
Learn SQL: SQL Server date and time functions
Learn SQL: Create SQL Server reports using date and time functions
Learn SQL: SQL Server Pivot Tables
Learn SQL: SQL Server export to Excel
Learn SQL: Intro to SQL Server loops
Learn SQL: SQL Server Cursors
Learn SQL: SQL Best Practices for Deleting and Updating data
学习SQL:CREATE DATABASE&CREATE TABLE操作
学习SQL:插入表
学习SQL:主键
学习SQL:外键
学习SQL:SELECT语句
学习SQL:INNER JOIN与LEFT JOIN
学习SQL:SQL脚本
学习SQL:关系类型
学习SQL:联接多个表
学习SQL:聚合函数
学习SQL:如何编写复杂的SELECT查询
学习SQL:INFORMATION_SCHEMA数据库
学习SQL:SQL数据类型
学习SQL:集合论
学习SQL:用户定义的函数
学习SQL:用户定义的存储过程
学习SQL:SQL视图
学习SQL:SQL触发器
学习SQL:练习SQL查询
学习SQL:SQL查询示例
学习SQL:使用SQL查询手动创建报告
学习SQL:SQL Server日期和时间函数
学习SQL:使用日期和时间函数创建SQL Server报表
学习SQL:SQL Server数据透视表
学习SQL:将SQL Server导出到Excel
学习SQL:SQL Server循环简介
学习SQL:SQL Server游标
学习SQL:删除和更新数据SQL最佳实践

翻译自: https://www.sqlshack.com/learn-sql-create-database-create-table/