sql语句语法多表关联_SQL创建表语句-带有示例语法

sql语句语法多表关联

SQL is one of the most reliable and straightforward querying languages around. It provides clear cut syntax that reads easily without abstracting away too much of the functionality's meaning.

SQL是最可靠,最直接的查询语言之一。 它提供了清晰易懂的语法,易于阅读,而又不会抽象出太多的功能含义。

If you'd like some history on the language as well as some interesting facts, check out the introduction portion of my SQL Update Statement article.  

如果您想了解某种语言的历史以及一些有趣的事实,请查看我的《 SQL更新语句》文章的介绍部分。

In this article, we're going to go through the important parts of creating a table in SQL.  My preferred "flavor" of SQL is SQL Server but the information about creating a table is fairly ubiquitous across all SQL variations.  

在本文中,我们将介绍在SQL中创建表的重要部分。 我最喜欢SQL“风味”是SQL Server,但是有关创建表的信息在所有SQL变体中都非常普遍。

If you've never used SQL or don't know what a table is, fear not! Briefly (and broadly), a table is a database object that holds, or contains, all of the data within that portion of the database. It stores this data in named columns and numbered rows which is not unfamiliar if you've ever used any spreadsheet program. Each row represents a whole database record.

如果您从未使用过SQL或不知道表是什么,请不要担心! 简要地(广义上),表是一个数据库对象,用于保存或包含数据库那部分中的所有数据。 它将数据存储在命名列和编号行中,如果您曾经使用过任何电子表格程序,这些都不是不熟悉的。 每行代表一个完整的数据库记录。

If data were in box form then a table would be a section of the warehouse shelving we store those boxes in.

如果数据是盒式的,那么表格将是我们将这些盒存储在其中的仓库货架的一部分。

sql语句语法多表关联_SQL创建表语句-带有示例语法
Photo by Nana Smirnova on Unsplash
Nana SmirnovaUnsplash上的照片

I'm simplifying the explanation greatly and there is much more to SQL tables but that's outside the scope of this article.  If you're itching for a more in-depth explanation on tables, I encourage you to dive into the Microsoft Database Design documentation.

我大大简化了解释,SQL表还有很多其他内容,但这不在本文的讨论范围之内。 如果您想对表进行更深入的说明,建议您深入阅读Microsoft数据库设计文档

Before we learn how to create the table, it's important that we learn what types of data these columns and rows can store.

在学习如何创建表之前,重要的是要了解这些列和行可以存储什么类型的数据。

资料类型 (Data Types)

SQL tables can hold text, numbers, a combination of text and numbers, as well as images and links.

SQL表可以保存文本,数字,文本和数字的组合以及图像和链接。

When creating our table, we designate the type of data its rows and columns will hold. Here are the overarching classifications of data:

创建表时,我们指定其行和列将保存的数据类型。 以下是数据的总体分类:

  • Approximate Numerics

    近似数值
  • Strings

    弦乐
  • Date & Time

    约会时间
  • Unicode Character Strings

    Unicode字符串
  • Exact Numerics

    精确数值
  • Other

    其他

I'll list some of the more commonly used data types below, but if you'd like a more on all data types, I invite you to check out this exhaustive article on each type from Microsoft.

我将在下面列出一些更常用的数据类型,但是如果您想了解所有数据类型的更多信息,我邀请您查看Microsoft每种类型的详尽文章

Here are the more commonly used types of data from my experience, in no particular order:

根据我的经验,以下是一些最常用的数据类型,不分先后顺序:

  • char(size) - fixed length string that can contain letters, numbers, special characters

    char(size)- 固定长度的字符串,可以包含字母,数字和特殊字符

  • varchar(size) - variable length string that can contain letters, numbers, & special characters

    varchar(size)- 可变长度的字符串,可以包含字母,数字和特殊字符

  • boolean - Zero (or values that equate to 0) is false, non-zero is true

    布尔值-零(或等于0的值)为false,非零为true
  • int(size optional) - a number up to 10 characters in length, accepts negative & positive numbers

    int( size可选 )-长度最大为10个字符的数字,可接受负数和正数

  • bigint(size optional) - a number up to 19 characters in length, accepts negative & positive numberrs

    bigint( size可选 )-长度最大为19个字符的数字,接受负号和正号

  • float(size, d) - a number with total number size represented by size and the number of characters after the decimal represented by the d

    float(size,d)-一个数字,其总大小由size表示,而小数点后的字符数由d表示

  • date - date in the format of YYYY-MM-DD

    date-日期,格式为YYYY-MM-DD

  • datetime - date time in the format of YYY-MM-DD hh:mm:ss

    datetime-日期时间,格式为YYY-MM-DD hh:mm:ss

  • time - time in the format of hh:mm:ss

    时间-时间,格式为hh:mm:ss

Alright, now that we know what types of data the rows and columns can contain let's get into the fun parts!

好了,现在我们知道行和列可以包含哪些数据类型,让我们进入有趣的部分!

建立表格 (Creating a Table)

sql语句语法多表关联_SQL创建表语句-带有示例语法
Photo by Nikhil Mitra on Unsplash
Nikhil MitraUnsplash拍摄的照片

Before we start it's important to note that I'll be providing all of my examples independent of any program.

在开始之前,请务必注意,我将提供与所有程序无关的所有示例。

However, if you'd like to start writing queries and you aren't sure where to start, take a look at SQL Server Management Studio. It's a free, robust program that's widely used and supported in the community.

但是,如果您想开始编写查询并且不确定从哪里开始,请查看SQL Server Management Studio。 这是一个免费,强大的程序,在社区中得到广泛使用和支持。

Alternatively, there are several options including DB Fiddle that allow you to build schemas and write queries right in your browser.  

另外,还有一些选项,包括DB Fiddle ,这些选项使您可以在浏览器中构建模式并编写查询。

Let's start with a simple statement to create a basic table:

让我们从创建基本表的简单语句开始:

CREATE TABLE table_name ( column1_name datatype, column2_name datatype, column3_name datatype, column4_name datatype, column5_name datatype,)CREATE TABLE table_name ( column1_name datatype, column2_name datatype, column3_name datatype, column4_name datatype, column5_name datatype,)

There are other parameters we can add after the datatype to augment the columns:

我们可以在datatype之后添加其他参数以增加列:

  • NOT NULL - passing this parameter will ensure the column cannot hold a NULL value

    NOT NULL传递此参数将确保列不能包含NULL

  • UNIQUE - passing this parameter will prevent the column from holding the same value more than once

    UNIQUE传递此参数将防止该列多次保存相同的值

  • UNIQUE KEY - passing this parameter will designate that column as a unique identifier. It is essentially a combination of the previous two parameters.

    UNIQUE KEY传递此参数将将该列指定为唯一标识符。 它本质上是前两个参数的组合。

Now, we're going to create a table (named doggo_info which must adhere to the identifier standards for databases) to hold information on the residents of Woof Woof Retreat, a fictional doggy daycare I just thought of :)

现在,我们将创建一个表(名为doggo_info,该表必须遵守数据库标识符标准 ),以保存有关Woof Woof Retreat居民的信息,Woof Woof Retreat是我刚刚想到的虚构的小狗日托:)

CREATE TABLE doggo_info ( ID int UNIQUE KEY, Name varchar(50) NOT NULL, Color varchar(50), Breed varchar(50), Age int, Weight int, Height int, Fav_Food varchar(100), Fav_Toy varchar(100), Dislikes varchar(500), Allergies varchar(500) NOT NULL ) CREATE TABLE doggo_info ( ID int UNIQUE KEY, Name varchar(50) NOT NULL, Color varchar(50), Breed varchar(50), Age int, Weight int, Height int, Fav_Food varchar(100), Fav_Toy varchar(100), Dislikes varchar(500), Allergies varchar(500) NOT NULL )

And here is the brand new table we just created:

这是我们刚创建的全新表:

Name Color Breed Age Weight Height Fav_Food Fav_Toy Dislikes Allergies
名称 颜色 品种 年龄 重量 高度 最喜欢的食物 收藏玩具 不喜欢 过敏症

You'll notice that our table is completely empty and this is because we haven't added any data to it yet. Doing so is beyond the scope of this article but I wanted you to be aware of that tidbit.

您会注意到我们的表完全为空,这是因为我们尚未向其添加任何数据。 这样做不在本文的讨论范围之内,但是我希望您意识到这一点。

从现有表创建表 (Create A Table From An Existing Table)

It is also possible to create a new table based off of an existing table.

也可以基于现有表创建新表。

It's pretty easy and doesn't require that much more syntax. We need to select the table and columns to "copy" from:

这非常简单,不需要太多语法。 我们需要从中选择要“复制”的表和列:

CREATE TABLE new_table_name AS SELECT column1, column2, column3, column4 (use * to select all columns to be added to the new_table) FROM current_table_name WHERE conditions_existCREATE TABLE new_table_name AS SELECT column1, column2, column3, column4 (use * to select all columns to be added to the new_table) FROM current_table_name WHERE conditions_exist

So, expediency's sake, I've added some data to our doggo_info table and it now looks like the example below:

因此,为了方便起见,我已经在我们的doggo_info表中添加了一些数据,现在看起来像下面的示例:

Name Color Breed Age Weight Height Fav_Food Fav_Toy Dislikes Allergies
daisy red standard dachshund 1 14 6 salmon flavored kibble squeeky ball birds flying over the yard cats, baths, cleanliness
chief black/tan rottweiler 3 41 17 literally anything rope tug staying off the couch listening, behaving, not slobbering on everything
sammie light honey golden retriever 9 46 19 beef flavored kibble her bed rambutcious puppies none known
名称 颜色 品种 年龄 重量 高度 最喜欢的食物 收藏玩具 不喜欢 过敏症
雏菊 标准腊肠犬 1个 14 6 鲑鱼粗磨 粘球 鸟儿飞过院子 猫,浴室,清洁
首席 黑色/棕褐色 罗威纳犬 3 41 17 几乎任何东西 绳拖船 不在沙发上 聆听,表现,不流连忘返
萨米 淡蜂蜜 金毛寻回犬 9 46 19 牛肉粗磨 她的床 贪婪的小狗 没有人知道

Now we can create another table based off of the data we have in our doggo_info table by running the query below:

现在,我们可以通过运行以下查询,基于doggo_info表中的数据创建另一个表:

CREATE TABLE puppies_only AS SELECT * FROM doggo_info WHERE Age < 4 CREATE TABLE puppies_only AS SELECT * FROM doggo_info WHERE Age < 4

We want to create a new table with all of the columns from the doggo_info table but only where the Age is less than 4. After running this query, our new table will look like this:

我们要创建一个新表,其中包含doggo_info表中的所有列,但仅Age小于4的表。运行此查询后,新表将如下所示:

Name Color Breed Age Weight Height Fav_Food Fav_Toy Dislikes Allergies
daisy red standard dachshund 1 14 6 salmon flavored kibble squeeky ball birds flying over the yard cats, baths, cleanliness
chief black/tan rottweiler 3 41 17 literally anything rope tug staying off the couch listening, behaving, not slobbering on everything
名称 颜色 品种 年龄 重量 高度 最喜欢的食物 收藏玩具 不喜欢 过敏症
雏菊 标准腊肠犬 1个 14 6 鲑鱼粗磨 粘球 鸟儿飞过院子 猫,浴室,清洁
首席 黑色/棕褐色 罗威纳犬 3 41 17 几乎任何东西 绳拖船 不在沙发上 聆听,表现,不流连忘返

I hope you can see just how powerful this statement can be.  With a few lines in our query we have essentially copied data from one table into another but only the rows that we wanted.  

希望您能看到此语句的功能。 在查询中只有几行,我们基本上已将数据从一个表复制到另一个表中,但仅复制了所需的行。

This is not only a handy tool to have in your developer tool belt – it'll save you untold amounts of time when you need to move data around tables.

这不仅是开发人员工具带中的方便工具,而且还可以在需要在表中移动数据时为您节省大量时间。

结语 (Wrapping Up)

Now that you know how to create (or copy) a table in SQL no matter what situation you're presented with, you can start filling the columns and rows with data to store!

既然您知道如何在SQL中创建(或复制)表,无论遇到什么情况,都可以开始用要存储的数据填充列和行!

The CREATE TABLE statement is extremely useful and powerful. You're ready to start putting it to good use.

CREATE TABLE语句非常有用且功能强大。 您已经准备好开始充分利用它。

If you found this article helpful check out my blog where I frequently post articles about web development, life, and learning.

如果您觉得这篇文章对您有帮助,请访问我的博客 ,我经常在其中发布有关Web开发,生活和学习的文章。

While you're there why not sign up for my newsletter? You can do that at the top right of the main blog page. I like to send out interesting articles (mine and others), resources, and tools for  developers every now and then.

当您在那里时,为什么不注册我的时事通讯? 您可以在博客主页面的右上角进行操作。 我喜欢不时为开发人员发送有趣的文章(我的和其他文章),资源和工具。

If you have questions about this article or just in general let me know – come say hi on Twitter or any of my other social media accounts which you can find below the  newsletter sign up on the main page of my blog or on my profile here at fCC :)

如果您对本文有疑问,或者只是一般而言,请告诉我–在Twitter或我的任何其他社交媒体帐户上打个招呼,您可以在新闻简报下方找到该消息,请在我的博客主页上或此处的我的个人资料上登录fCC :)

Have an awesome day! Happy learning and happy coding, friend!

祝你有美好的一天! 祝您学习愉快,编码愉快,朋友!

翻译自: https://www.freecodecamp.org/news/sql-create-table-statement-with-example-syntax/

sql语句语法多表关联