Home Database Mysql Tutorial Basics of SQL Data Operations (Intermediate) 8

Basics of SQL Data Operations (Intermediate) 8

Dec 17, 2016 pm 02:36 PM

Update records

To modify one or more records that already exist in the table, SQL should be used UPDATE statement. Like the DELETE statement, the UPDATE statement can use the WHERE clause to select specific records to update. Please see this example:

UPDATE mytable SET first_column=’Updated!’ WHERE second_column=’Update Me!’

This UPDATE The statement updates the value of all second_column fields to 'Update Me!’ record. For all selected records, the value of the first_column field is set to 'Updated!'.

The following is the complete syntax of the UPDATE statement:

UPDATE {table_name|view_name} SET [{table_name|view_name}]

{column_list|variable_list|variable_and_column_list}

[,{column_list2|variable_list2|variable_and_column_list2}…

[,{column_listN|variable_listN|variable_and_column_listN}]]

[WHERE clause]

Note:

You can use the UPDATE statement for text fields. However, if you need to update a very long string, you should use the UPDATETEXT statement. This material is too advanced for this book and will not be discussed. For more information, please refer to Microsoft SQL Server documentation.

If you do not provide a WHERE clause, all records in the table will be updated. Sometimes this is useful. For example, if you want to double the price of all books in the titles table, you can use UPDATE as follows Statement:

You can also update multiple fields at the same time. For example, the following UPDATE statement simultaneously updates the three fields first_column, second_column, and third_column:

UPDATE mytable SET first_column=’Updated!’

Second_column=’Updated!’

Third_column=’Updated!’

WHERE first_column=’Update Me1’

Tip:

SQL ignores extra spaces in statements. You can write SQL statements in whatever format is easiest for you to read.

 

Use SELECT Create records and tables

You may have noticed that INSERT The statement is a little different from the DELETE statement and UPDATE statement in that it only operates one record at a time. However, there is a way to make INSERT statement to add multiple records at once. To do this, you need to combine an INSERT statement with a SELECT statement, like this:

INSERT mytable (first_column,second_column)

SELECT another_first,another_second

FROM anothertable

WHERE another_first=’Copy Me!’

This statement copies records from anothertable to mytable. Only the value of the field another_first in the table anothertable is ‘Copy Me! ’ records are copied.

When creating a backup of records in a table, this form of INSERT Statements are very useful. You can use this method to copy records from one table to another table before deleting them.

If you need to copy the entire table, you can use SELECT INTO statement. For example, the following statement creates a new table named newtable that contains all the data for table mytable:

SELECT * INTO newtable FROM mytable

You can also specify that only specific fields are used to create this new table. To do this, simply specify the fields you want to copy in the field list. Alternatively, you can use WHERE clause to limit the records copied to the new table. The following example only copies the value of the field second_columnd equal to 'Copy Me!’ first_column field of the record.

SELECT first_column INTO newtable

FROM mytable

WHERE second_column=’Copy Me!’

It is difficult to modify an already created table using SQL. For example, if you add a field to a table, there is no easy way to remove it. Additionally, if you accidentally give a field the wrong data type, you won't be able to change it. However, using the SQL statements described in this section, you can bypass both problems.

For example, suppose you want to delete a field from a table. Use SELECT INTO statement, you can create a copy of the table without the fields you want to delete. This allows you to delete the field while retaining the data you don't want to delete.

If you want to change the data type of a field, you can create a new table containing fields of the correct data type. Once the table is created, you can use the UPDATE statement with SELECT statement to copy all data in the original table to the new table. Through this method, you can modify the structure of the table and save the original data.

Aggregation Functions

Up to now, you have only learned how to retrieve one or more records from a table based on specific conditions. However, suppose you want to perform statistics on records in a table. For example, if you want to count the results of a poll stored in a table. Or you want to know how much time a visitor spends on your site on average. To perform statistics on any type of data in a table, you need to use aggregate functions.

Microsoft SQL Five types of aggregate functions are supported. You can count the number of records, average, minimum, maximum, or sum. When you use an aggregate function, it simply returns a number that represents one of these statistical values.

Note:

To use the return value of a set function in your asp web page, you need to give the value a name. To do this, you can follow the aggregate function with a field name in the SELECT statement, as in the following example:

SELECT AVG(vote) ‘the_average’ FROM opinion

In this example, the average of votes is named the_average. Now you can use this name in the database method of your ASP web page.

Counts the number of field values ​​

The function COUNT() is perhaps the most useful aggregate function. You can use this function to count how many records there are in a table. Here's an example:

SELECT COUNT(au_lname) FROM authors

This example calculates the name in the table authors (last name) number. If the same name appears more than once, the name will be counted multiple times. If you want to know how many authors have a specific name, you can use the WHERE clause, as in the following example:

SELECT COUNT(au_lname) FROM authors WHERE au_lname=’Ringer’

This example returns the number of authors named ‘Ringer’. If the name appears twice in the authors table, the return value of this function is 2.

Suppose you want to know the number of authors with different names. You can get this number by using the keyword DISTINCT. As shown in the following example:

SELECT COUNT(DISTINCT au_lname) FROM authors

If the name 'Ringer' appears more than once, it will only be counted once. keywordDISTINCT It is decided that only values ​​that are different from each other are calculated.

Normally, when you use COUNT(), null values ​​in fields will be ignored. Generally speaking, this is what you want. However, if you just want to know the number of records in the table, then you need to count all records in the table - regardless of whether it contains null values. Here's an example of how to do this:

SELECT COUNT(*) FROM authors

Note that the function COUNT() does not specify any fields. This statement counts all records in the table, including records with null values. Therefore, you do not need to specify specific fields to be calculated.

The function COUNT() is useful in many different situations. For example, suppose you have a table that holds the results of a poll on the quality of your site. This table has a field called vote, the value of this field is either 0 or 1. 0 means a negative vote, and 1 means a positive vote. To determine the number of upvotes you can SELECT all the following Statement:

SELECT COUNT(vote) FROM opinion_table WHERE vote=1

Calculate the average of a field

Using the function COUNT(), you can count how many values ​​there are in a field. But sometimes you need to calculate the average of these values. Using the function AVG() you can return the average of all values ​​in a field.

Suppose you conduct a more complex poll on your site. Visitors can vote from 1 to 10 to indicate how much they like your site. You save the voting results in an INT type field called vote. To calculate the average of your user votes you need to use the function AVG():

SELECT AVG(vote) FROM opinion

The return value of this SELECT statement represents the average user preference for your site. The function AVG() can only be used for numeric fields. This function also ignores null values ​​when calculating the average.

Calculate the sum of field values ​​

Assume that your site is used to sell cards and has been running for two months. It’s time to calculate how much money you made. Suppose there is a table named orders to record the order information of all visitors. To calculate the sum of all ordered quantities you can use the function SUM():

SELECT SUM(purchase_amount) FROM The return value of the orders

function SUM() represents the average of all values ​​in the field purchase_amount. The data type of the field purchase_amount may be MONEY, but you can also use the function SUM() for other numeric fields.

Return the maximum or minimum value

Once again, assume you have a table that holds the results of a poll on your site. Visitors can choose from 1 to 10 The value represents their evaluation of your site. If you want to know the highest rating that visitors have for your site, you can use the following statement:

SELECT MAX(vote) FROM opinion

You may hope that someone has given your site a high opinion. Through the function MAX(), you can know the maximum value among all values ​​of a numeric field. If someone voted the number 10 on your site, the function MAX() will return that value.

On the other hand, if you want to know the lowest rating of your site by visitors, you can use the function MIN(), as shown in the following example:

SELECT MIN(vote) FROM opinion

The function MIN() returns the minimum value among all values ​​of a field. If the field is empty, function MIN() returns a null value.

Other commonly used SQL expressions, functions, and procedures

This section will introduce some other SQL technologies. You'll learn how to retrieve data from a table whose field values ​​fall within a certain range. You'll also learn how to convert field values ​​from one type to another, and how to manipulate string and datetime data. Finally, you'll learn a simple way to send an email.

Get data out by matching a range of values

Suppose you have a table that holds the results of a poll on your site. Now you want to send a written thank you note to all visitors who rated your site between 7 and 10. To get the names of these people, you can use the following SELECT Statement:

SELECT username FROM opinion WHERE vote>6 and vote<11

This SELECT statement will achieve your requirements. You can also get the same result using the following SELECT statement:

SELECT username FROM opinion WHERE vote BETWEEN 7 AND 10

thisSELECT statement is equivalent to the previous statement. Which statement to use is a matter of programming style, but you will find that using the expression BETWEEN statements are easier to read.

Now let’s say you only want to extract the names of visitors who voted 1 or 10 for your site. To retrieve these names from the opinion table, you can use the following SELECT Statement:

SELECT username FROM opinion WHERE vote=1 or vote

This SELECT statement will return the correct results, there is no reason not to use it. However, there is an equivalent way. You can get the same result using SELECT like this:

SELECT username FROM opinion WHERE vote IN (1,10)

Pay attention to the use of expression IN. This SELECT The statement only retrieves records whose vote value is equal to one of the values ​​in parentheses.

You can also use IN to match character data. For example, let's say you only want to extract the vote values ​​of Bill Gates or President Clinton. You can use SELECT as follows Statement:

SELECT vote FROM opinion WHERE username IN (‘Bill Gates’,’President Clinton’)

Finally, you can use the expression NOT along with BETWEEN or IN. For example, to retrieve the names of people whose vote value is not between 7 and 10, you can use the following SELECT Statement:

SELECT username FROM opinion WHERE vote NOT BETWEEN 7 and 10

To select records whose value in a certain field is not in a list of values, you can use NOT and IN at the same time, as shown in the following example:

SELECT vote FROM opinion

WHERE username NOT IN (‘Bill Gates’,’President Clinton’)

You are not required to use BETWEEN or IN in your SQL statement, however, to make your query closer to natural language, these two expressions are helpful.


The above is the content of SQL Data Operation Basics (Intermediate) 8. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

What does the identity attribute in SQL mean? What does the identity attribute in SQL mean? Feb 19, 2024 am 11:24 AM

What is Identity in SQL? Specific code examples are needed. In SQL, Identity is a special data type used to generate auto-incrementing numbers. It is often used to uniquely identify each row of data in a table. The Identity column is often used in conjunction with the primary key column to ensure that each record has a unique identifier. This article will detail how to use Identity and some practical code examples. The basic way to use Identity is to use Identit when creating a table.

How to use PHP to implement batch processing and data batch operations How to use PHP to implement batch processing and data batch operations Sep 06, 2023 am 10:46 AM

How to use PHP to implement batch processing and data batch operations. In the process of developing web applications, we often encounter situations where multiple pieces of data need to be processed at the same time. In order to improve efficiency and reduce the number of database requests, we can use PHP to implement batch processing and data batch operations. This article will introduce how to use PHP to implement these functions, and attach code examples for reference. Batch processing of data When you need to perform the same operation on a large amount of data, you can use PHP's loop structure for batch processing.

How to solve the 5120 error in SQL How to solve the 5120 error in SQL Mar 06, 2024 pm 04:33 PM

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

How to use SQL statements for data aggregation and statistics in MySQL? How to use SQL statements for data aggregation and statistics in MySQL? Dec 17, 2023 am 08:41 AM

How to use SQL statements for data aggregation and statistics in MySQL? Data aggregation and statistics are very important steps when performing data analysis and statistics. As a powerful relational database management system, MySQL provides a wealth of aggregation and statistical functions, which can easily perform data aggregation and statistical operations. This article will introduce the method of using SQL statements to perform data aggregation and statistics in MySQL, and provide specific code examples. 1. Use the COUNT function for counting. The COUNT function is the most commonly used

See all articles