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
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)!

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
