基本SQL命令-您應該知道的數據庫查詢和語句列表

SQL stands for Structured Query Language. SQL commands are the instructions used to communicate with a database to perform tasks, functions, and queries with data.

SQL代表結構化查詢語言。 SQL命令是用于與數據庫通信以執行任務,功能和數據查詢的指令。

SQL commands can be used to search the database and to do other functions like creating tables, adding data to tables, modifying data, and dropping tables.

SQL命令可用于搜索數據庫并執行其他功能,例如創建表,向表中添加數據,修改數據和刪除表。

Here is a list of basic SQL commands (sometimes called clauses) you should know if you are going to work with SQL.

這是基本SQL命令(有時稱為子句)的列表,您應該知道是否要使用SQL。

選擇和從 (SELECT and FROM)

The SELECT part of a query determines which columns of the data to show in the results. There are also options you can apply to show data that is not a table column.

查詢的SELECT部分確定要在結果中顯示數據的哪些列。 您還可以應用其他選項來顯示不是表列的數據。

The example below shows three columns SELECTed FROM the “student” table and one calculated column. The database stores the studentID, FirstName, and LastName of the student. We can combine the First and the Last name columns to create the FullName calculated column.

下例顯示了FROM “學生”表中SELECT三列和一個計算所得的列。 該數據庫存儲該學生的studentID,FirstName和LastName。 我們可以組合名字和姓氏列來創建FullName計算列。

SELECT studentID, FirstName, LastName, FirstName + ' ' + LastName AS FullName
FROM student;
+-----------+-------------------+------------+------------------------+
| studentID | FirstName         | LastName   | FullName               |
+-----------+-------------------+------------+------------------------+
|         1 | Monique           | Davis      | Monique Davis          |
|         2 | Teri              | Gutierrez  | Teri Gutierrez         |
|         3 | Spencer           | Pautier    | Spencer Pautier        |
|         4 | Louis             | Ramsey     | Louis Ramsey           |
|         5 | Alvin             | Greene     | Alvin Greene           |
|         6 | Sophie            | Freeman    | Sophie Freeman         |
|         7 | Edgar Frank "Ted" | Codd       | Edgar Frank "Ted" Codd |
|         8 | Donald D.         | Chamberlin | Donald D. Chamberlin   |
|         9 | Raymond F.        | Boyce      | Raymond F. Boyce       |
+-----------+-------------------+------------+------------------------+
9 rows in set (0.00 sec)

創建表 (CREATE TABLE)

CREATE TABLE does just what it sounds like: it creates a table in the database. You can specify the name of the table and the columns that should be in the table.

CREATE TABLE功能聽起來很像:它在數據庫中創建一個表。 您可以指定表的名稱以及應在表中的列。

CREATE TABLE table_name (column_1 datatype,column_2 datatype,column_3 datatype
);

更改表 (ALTER TABLE)

ALTER TABLE changes the structure of a table. Here is how you would add a column to a database:

ALTER TABLE更改ALTER TABLE的結構。 這是將列添加到數據庫的方法:

ALTER TABLE table_name
ADD column_name datatype;

檢查 (CHECK)

The CHECK constraint is used to limit the value range that can be placed in a column.

CHECK約束用于限制可以放置在列中的值范圍。

If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

如果在單個列上定義CHECK約束,則該列僅允許某些值。 如果在表上定義CHECK約束,則可以基于行中其他列中的值來限制某些列中的值。

The following SQL creates a CHECK constraint on the “Age” column when the “Persons” table is created. The CHECK constraint ensures that you can not have any person below 18 years.

創建“人員”表時,以下SQL在“年齡”列上創建CHECK約束。 CHECK約束確保您不能有18歲以下的任何人。

CREATE TABLE Persons (ID int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Age int,CHECK (Age>=18)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

若要命名CHECK約束,并在多個列上定義CHECK約束,請使用以下SQL語法:

CREATE TABLE Persons (ID int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Age int,City varchar(255),CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

哪里 (WHERE)

(AND, OR, IN, BETWEEN, and LIKE)

( ANDOR INBETWEENLIKE )

The WHERE clause is used to limit the number of rows returned.

WHERE子句用于限制返回的行數。

As an example, first we will show you a SELECT statement and results without a WHERE statement. Then we will add a WHERE statement that uses all five qualifiers above.

作為示例,首先我們將向您顯示SELECT語句和WHERE語句的結果。 然后,我們將添加一個使用上面所有五個限定詞的WHERE語句。

SELECT studentID, FullName, sat_score, rcd_updated FROM student;
+-----------+------------------------+-----------+---------------------+
| studentID | FullName               | sat_score | rcd_updated         |
+-----------+------------------------+-----------+---------------------+
|         1 | Monique Davis          |       400 | 2017-08-16 15:34:50 |
|         2 | Teri Gutierrez         |       800 | 2017-08-16 15:34:50 |
|         3 | Spencer Pautier        |      1000 | 2017-08-16 15:34:50 |
|         4 | Louis Ramsey           |      1200 | 2017-08-16 15:34:50 |
|         5 | Alvin Greene           |      1200 | 2017-08-16 15:34:50 |
|         6 | Sophie Freeman         |      1200 | 2017-08-16 15:34:50 |
|         7 | Edgar Frank "Ted" Codd |      2400 | 2017-08-16 15:35:33 |
|         8 | Donald D. Chamberlin   |      2400 | 2017-08-16 15:35:33 |
|         9 | Raymond F. Boyce       |      2400 | 2017-08-16 15:35:33 |
+-----------+------------------------+-----------+---------------------+
9 rows in set (0.00 sec)

Now, we'll repeat the SELECT query but we'll limit the rows returned using a WHERE statement.

現在,我們將重復執行SELECT查詢,但是將限制使用WHERE語句返回的行。

STUDENT studentID, FullName, sat_score, recordUpdated
FROM student
WHERE (studentID BETWEEN 1 AND 5 OR studentID = 8)ANDsat_score NOT IN (1000, 1400);
+-----------+----------------------+-----------+---------------------+
| studentID | FullName             | sat_score | rcd_updated         |
+-----------+----------------------+-----------+---------------------+
|         1 | Monique Davis        |       400 | 2017-08-16 15:34:50 |
|         2 | Teri Gutierrez       |       800 | 2017-08-16 15:34:50 |
|         4 | Louis Ramsey         |      1200 | 2017-08-16 15:34:50 |
|         5 | Alvin Greene         |      1200 | 2017-08-16 15:34:50 |
|         8 | Donald D. Chamberlin |      2400 | 2017-08-16 15:35:33 |
+-----------+----------------------+-----------+---------------------+
5 rows in set (0.00 sec)

更新 (UPDATE)

To update a record in a table you use the UPDATE statement.

要更新表中的記錄,請使用UPDATE語句。

Use the WHERE condition to specify which records you want to update. It is possible to update one or more columns at a time. The syntax is:

使用WHERE條件指定要更新的記錄。 可以一次更新一個或多個列。 語法為:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Here is an example updating the Name of the record with Id 4:

這是一個使用ID 4更新記錄名稱的示例:

UPDATE Person
SET Name = “Elton John”
WHERE Id = 4;

You can also update columns in a table by using values from other tables. Use the JOIN clause to get data from multiple tables. The syntax is:

您還可以通過使用其他表中的值來更新表中的列。 使用JOIN子句從多個表中獲取數據。 語法為:

UPDATE table_name1
SET table_name1.column1 = table_name2.columnAtable_name1.column2 = table_name2.columnB
FROM table_name1
JOIN table_name2 ON table_name1.ForeignKey = table_name2.Key

Here is an example updating Manager of all records:

這是所有記錄的更新管理器的示例:

UPDATE Person
SET Person.Manager = Department.Manager
FROM Person
JOIN Department ON Person.DepartmentID = Department.ID

通過...分組 (GROUP BY)

GROUP BY allows you to combine rows and aggregate data.

GROUP BY使您可以合并行并匯總數據。

Here is the syntax of GROUP BY:

這是GROUP BY的語法:

SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name;

擁有 (HAVING)

HAVING allows you to filter the data aggregated by the GROUP BY clause so that the user gets a limited set of records to view.

HAVING允許您過濾GROUP BY子句聚合的數據,以便用戶獲得一組有限的記錄以供查看。

Here is the syntax of HAVING:

這是HAVING的語法:

SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > value;

AVG() (AVG())

“Average” is used to calculate the average of a numeric column from the set of rows returned by a SQL statement.

“平均值”用于從SQL語句返回的行集中計算數字列的平均值。

Here is the syntax for using the function:

這是使用該函數的語法:

SELECT groupingField, AVG(num_field)
FROM table1
GROUP BY groupingField

Here’s an example using the student table:

這是使用學生表的示例:

SELECT studentID, FullName, AVG(sat_score) 
FROM student 
GROUP BY studentID, FullName;

(AS)

AS allows you to rename a column or table using an alias.

AS允許您使用別名重命名列或表。

SELECT user_only_num1 AS AgeOfServer, (user_only_num1 - warranty_period) AS NonWarrantyPeriod FROM server_table

This results in output as below.

結果如下。

+-------------+------------------------+
| AgeOfServer | NonWarrantyPeriod      | 
+-------------+------------------------+
|         36  |                     24 |
|         24  |                     12 | 
|         61  |                     49 |
|         12  |                      0 | 
|          6  |                     -6 |
|          0  |                    -12 | 
|         36  |                     24 |
|         36  |                     24 | 
|         24  |                     12 | 
+-------------+------------------------+

You can also use AS to assign a name to a table to make it easier to reference in joins.

您還可以使用AS為表分配名稱,以使其更易于在聯接中引用。

SELECT ord.product, ord.ord_number, ord.price, cust.cust_name, cust.cust_number FROM customer_table AS custJOIN order_table AS ord ON cust.cust_number = ord.cust_number

This results in output as below.

結果如下。

+-------------+------------+-----------+-----------------+--------------+
| product     | ord_number | price     | cust_name       | cust_number  |
+-------------+------------+-----------+-----------------+--------------+
|     RAM     |   12345    |       124 | John Smith      |  20          |
|     CPU     |   12346    |       212 | Mia X           |  22          |
|     USB     |   12347    |        49 | Elise Beth      |  21          |
|     Cable   |   12348    |         0 | Paul Fort       |  19          |
|     Mouse   |   12349    |        66 | Nats Back       |  15          |
|     Laptop  |   12350    |       612 | Mel S           |  36          |
|     Keyboard|   12351    |        24 | George Z        |  95          |
|     Keyboard|   12352    |        24 | Ally B          |  55          |
|     Air     |   12353    |        12 | Maria Trust     |  11          |
+-------------+------------+-----------+-----------------+--------------+

訂購 (ORDER BY)

ORDER BY gives us a way to sort the result set by one or more of the items in the SELECT section. Here is an SQL sorting the students by FullName in descending order. The default sort order is ascending (ASC) but to sort in the opposite order (descending) you use DESC.

ORDER BY提供了一種方法,可以按SELECT部分中的一個或多個項目對結果集進行排序。 這是一個按FullName降序對學生進行排序SQL。 默認的排序順序是升序( ASC ),但要使用相反的順序(降序),請使用DESC

SELECT studentID, FullName, sat_score
FROM student
ORDER BY FullName DESC;

計數 (COUNT)

COUNT will count the number of rows and return that count as a column in the result set.

COUNT將對行數進行計數,并將該計數作為列返回到結果集中。

Here are examples of what you would use COUNT for:

以下是將COUNT用于以下用途的示例:

  • Counting all rows in a table (no group by required)

    計算表中的所有行(不需要按組)
  • Counting the totals of subsets of data (requires a Group By section of the statement)

    計算數據子集的總數(需要語句的“分組依據”部分)

This SQL statement provides a count of all rows. Note that you can give the resulting COUNT column a name using “AS”.

該SQL語句提供所有行的計數。 請注意,您可以使用“ AS”為所得的COUNT列命名。

SELECT count(*) AS studentCount FROM student;

刪除 (DELETE)

DELETE is used to delete a record in a table.

DELETE用于刪除表中的記錄。

Be careful. You can delete all records of the table or just a few. Use the WHERE condition to specify which records you want to delete. The syntax is:

小心。 您可以刪除表中的所有記錄或僅刪除一些記錄。 使用WHERE條件指定要刪除的記錄。 語法為:

DELETE FROM table_name
WHERE condition;

Here is an example deleting from the table Person the record with Id 3:

這是從表Person中刪除ID為3的記錄的示例:

DELETE FROM Person
WHERE Id = 3;

內部聯接 (INNER JOIN)

JOIN, also called Inner Join, selects records that have matching values in two tables.

JOIN (也稱為內部聯接)選擇兩個表中具有匹配值的記錄。

SELECT * FROM A x JOIN B y ON y.aId = x.Id

左聯接 (LEFT JOIN)

A LEFT JOIN returns all rows from the left table, and the matched rows from the right table. Rows in the left table will be returned even if there was no match in the right table. The rows from the left table with no match in the right table will have null for right table values.

LEFT JOIN返回左側表中的所有行,以及右側表中的匹配行。 即使右表中沒有匹配項,也將返回左表中的行。 左表中沒有匹配項的行在右表中將為null對于右表值。

SELECT * FROM A x LEFT JOIN B y ON y.aId = x.Id

正確加入 (RIGHT JOIN)

A RIGHT JOIN returns all rows from the right table, and the matched rows from the left table. Opposite of a left join, this will return all rows from the right table even where there is no match in the left table. Rows in the right table that have no match in the left table will have null values for left table columns.

RIGHT JOIN返回右側表中的所有行,以及左側表中的匹配行。 與左聯接相反,這將返回右表中的所有行,即使左表中沒有匹配項也是如此。 右表中與左表不匹配的行的左表列將具有null值。

SELECT * FROM A x RIGHT JOIN B y ON y.aId = x.Id

全外連接 (FULL OUTER JOIN)

A FULL OUTER JOIN returns all rows for which there is a match in either of the tables. So if there are rows in the left table that do not have matches in the right table, those will be included. Also, if there are rows in the right table that do not have matches in the left table, those will be included.

FULL OUTER JOIN返回所有表中都匹配的所有行。 因此,如果左表中的行與右表中的行不匹配,則將這些行包括在內。 另外,如果右表中的行與左表中的行不匹配,則將這些行包括在內。

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName

(INSERT)

INSERT is a way to insert data into a table.

INSERT是一種將數據插入表中的方法。

INSERT INTO table_name (column_1, column_2, column_3) 
VALUES (value_1, 'value_2', value_3);

喜歡 (LIKE)

LIKE ?is used in a WHERE or HAVING (as part of the GROUP BY) to limit the selected rows to the items when a column has a certain pattern of characters contained in it.

LIKEWHEREHAVING (作為GROUP BY一部分)用于在列中包含某些特定字符模式的情況下,將選定的行限制為項目。

This SQL will select students that have FullName starting with “Monique” or ending with “Greene”.

這個SQL將選擇具有學生FullName開頭“莫妮克”或“格林”的結局。

SELECT studentID, FullName, sat_score, rcd_updated
FROM student 
WHERE FullName LIKE 'Monique%' OR FullName LIKE '%Greene';
+-----------+---------------+-----------+---------------------+
| studentID | FullName      | sat_score | rcd_updated         |
+-----------+---------------+-----------+---------------------+
|         1 | Monique Davis |       400 | 2017-08-16 15:34:50 |
|         5 | Alvin Greene  |      1200 | 2017-08-16 15:34:50 |
+-----------+---------------+-----------+---------------------+
2 rows in set (0.00 sec)

You can place NOT before LIKE to exclude the rows with the string pattern instead of selecting them. This SQL excludes records that contain “cer Pau” and “Ted” in the FullName column.

你可以把NOTLIKE與字符串模式排除行,而不是選擇他們的。 該SQL排除FullName列中包含“ cer Pau”和“ Ted”的記錄。

SELECT studentID, FullName, sat_score, rcd_updated
FROM student 
WHERE FullName NOT LIKE '%cer Pau%' AND FullName NOT LIKE '%"Ted"%';
+-----------+----------------------+-----------+---------------------+
| studentID | FullName             | sat_score | rcd_updated         |
+-----------+----------------------+-----------+---------------------+
|         1 | Monique Davis        |       400 | 2017-08-16 15:34:50 |
|         2 | Teri Gutierrez       |       800 | 2017-08-16 15:34:50 |
|         4 | Louis Ramsey         |      1200 | 2017-08-16 15:34:50 |
|         5 | Alvin Greene         |      1200 | 2017-08-16 15:34:50 |
|         6 | Sophie Freeman       |      1200 | 2017-08-16 15:34:50 |
|         8 | Donald D. Chamberlin |      2400 | 2017-08-16 15:35:33 |
|         9 | Raymond F. Boyce     |      2400 | 2017-08-16 15:35:33 |
+-----------+----------------------+-----------+---------------------+
7 rows in set (0.00 sec)

翻譯自: https://www.freecodecamp.org/news/basic-sql-commands/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390797.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390797.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390797.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode 5756. 兩個數組最小的異或值之和(狀態壓縮dp)

題目 給你兩個整數數組 nums1 和 nums2 ,它們長度都為 n 。 兩個數組的 異或值之和 為 (nums1[0] XOR nums2[0]) (nums1[1] XOR nums2[1]) … (nums1[n - 1] XOR nums2[n - 1]) (下標從 0 開始)。 比方說,[1,2,3] 和 [3,2,1…

客戶細分模型_Avarto金融解決方案的客戶細分和監督學習模型

客戶細分模型Lets assume that you are a CEO of a company which have some X amount of customers in a city with 1000 *X population. Analyzing the trends/features of your customer and segmenting the population of the city to land new potential customers would …

用 Go 編寫一個簡單的 WebSocket 推送服務

用 Go 編寫一個簡單的 WebSocket 推送服務 本文中代碼可以在 github.com/alfred-zhon… 獲取。 背景 最近拿到需求要在網頁上展示報警信息。以往報警信息都是通過短信,微信和 App 推送給用戶的,現在要讓登錄用戶在網頁端也能實時接收到報警推送。 依稀記…

leetcode 231. 2 的冪

給你一個整數 n,請你判斷該整數是否是 2 的冪次方。如果是,返回 true ;否則,返回 false 。 如果存在一個整數 x 使得 n 2x ,則認為 n 是 2 的冪次方。 示例 1: 輸入:n 1 輸出:tr…

Java概述、環境變量、注釋、關鍵字、標識符、常量

Java語言的特點 有很多小特點,重點有兩個開源,跨平臺 Java語言是跨平臺的 Java語言的平臺 JavaSE JavaME--Android JavaEE DK,JRE,JVM的作用及關系(掌握) (1)作用 JVM:保證Java語言跨平臺 &#xff0…

寫游戲軟件要學什么_為什么要寫關于您所知道的(或所學到的)的內容

寫游戲軟件要學什么Im either comfortably retired or unemployed, I havent decided which. What I do know is that I am not yet ready for decades of hard-won knowledge to lie fallow. Still driven to learn new technologies and to develop new projects, I see the …

leetcode 342. 4的冪

給定一個整數,寫一個函數來判斷它是否是 4 的冪次方。如果是,返回 true ;否則,返回 false 。 整數 n 是 4 的冪次方需滿足:存在整數 x 使得 n 4x 示例 1: 輸入:n 16 輸出:true …

梯度反傳_反事實政策梯度解釋

梯度反傳Among many of its challenges, multi-agent reinforcement learning has one obstacle that is overlooked: “credit assignment.” To explain this concept, let’s first take a look at an example…在許多挑戰中,多主體強化學習有一個被忽略的障礙&a…

三款功能強大代碼比較工具Beyond compare、DiffMerge、WinMerge

我們經常會遇到需要比較同一文件的不同版本,特別是代碼文件。如果人工去對比查看,勢必費時實力還會出現紕漏和錯誤,因此我們需要借助一些代碼比較的工具來自動完成這些工作。這里介紹3款比較流行且功能強大的工具。 1. Beyond compare這是一款…

shell腳本_Shell腳本

shell腳本In the command line, a shell script is an executable file that contains a set of instructions that the shell will execute. Its main purpose is to reduce a set of instructions (or commands) in just one file. Also it can handle some logic because it…

大數據與Hadoop

大數據的定義 大數據是指無法在一定時間內用常規軟件工具對其內容進行抓取、管理和處理的數據集合。 大數據的概念–4VXV 1,數據量大(Volume)2,類型繁多(Variety )3,速度快時效高(Velocity)4,價值密度低…

Arm匯編指令學習

ARM指令格式 ARM指令格式解析 opcode: 指令助記符,例如,MOV ,ADD,SUB等等 cond:指令條件碼表.下面附一張圖 {S}:是否影響CPSR的值. {.W .N}:指令寬度說明符,無論是ARM代碼還是Thumb(armv6t2或更高版本)代碼都可以在其中使用.W寬度說明符&…

facebook.com_如何降低電子商務的Facebook CPM

facebook.comWith the 2020 election looming, Facebook advertisers and e-commerce stores are going to continually see their ad costs go up as the date gets closer (if they haven’t already).隨著2020年選舉的臨近,隨著日期越來越近,Facebook…

Python中的If,Elif和Else語句

如果Elif Else聲明 (If Elif Else Statements) The if/elif/else structure is a common way to control the flow of a program, allowing you to execute specific blocks of code depending on the value of some data.if / elif / else結構是控制程序流程的常用方法&#x…

Hadoop安裝及配置

Hadoop的三種運行模式 單機模式(Standalone,獨立或本地模式):安裝簡單,運行時只啟動單個進程,僅調試用途;偽分布模式(Pseudo-Distributed):在單節點上同時啟動namenode、datanode、secondarynamenode、resourcemanage…

漏洞發布平臺-安百科技

一個不錯的漏洞發布平臺:https://vul.anbai.com/ 轉載于:https://blog.51cto.com/antivirusjo/2093758

Android 微信分享圖片

private String APP_ID "00000000000000000"; //微信 APPID private IWXAPI iwxapi; private void regToWx() {iwxapi WXAPIFactory.createWXAPI(context, APP_ID, true);//這里context記得初始化iwxapi.registerApp(APP_ID); } IMServer.getDiskBitmap(IMServer.u…

蒙蒂霍爾問題_常見的邏輯難題–騎士和刀,蒙蒂·霍爾和就餐哲學家的問題解釋...

蒙蒂霍爾問題While not strictly related to programming, logic puzzles are a good warm up to your next coding session. You may encounter a logic puzzle in your next technical interview as a way to judge your problem solving skills, so its worth being prepare…

西格爾零點猜想_我從埃里克·西格爾學到的東西

西格爾零點猜想I finished reading Eric Siegel’s Predictive Analytics. And I have to say it was an awesome read. How do I define an awesome or great book? A book that changes your attitude permanently. You must not be the same person that you were before y…

C/C++實現刪除字符串的首尾空格

StdStringTrimTest.cpp #include <iostream> int main() {std::string str(" 字符串 String ");std::cout << str << std::endl;std::cout << str.size() << std::endl;str.erase(str.find_first_of( ), str.find_first_not_of…