MySQL - written test questions

Analysis:

To query the maximum score for each subject, you can use the following SQL statement:

SELECT coursename, MAX(score) 
FROM t_stuscore
GROUP BY coursename;

This SQL statement uses the `MAX()` aggregate function to obtain the maximum score for each subject and uses the `GROUP BY` clause to group by subjects. The result will return the maximum score for each subject and the corresponding subject name.

 Analysis:

A. The COUNT function can be used not only for CHAR, VARCHAR and NUMBER data types, it can be used for any data type

B. Correct

C. To count the number of rows in a column in SQL, you should use COUNT(*) or COUNT(column name)

D. A SELECT statement using the COUNT function with the DISTINCT keyword can contain a WHERE clause. The WHERE clause is used to filter rows that meet specific criteria, while the DISTINCT keyword is used to eliminate duplicate values. These two keywords can be used at the same time to obtain row count statistics that meet the conditions and are deduplicated.

Analysis:

The correct SQL statement is:

UPDATE t_stuscore
SET score = score + 5
WHERE coursename = '化学';

This SQL statement uses the UPDATE statement to update data in the t_stuscore table. It will select all records with the subject name 'Chemistry' and add 5 points to the corresponding scores. Through the WHERE clause, you can specify that only records that meet the criteria should be updated.

 Analysis:

The condition `BETWEEN 15 AND 35` means that the age is between 15 and 35. According to the syntax rules of SQL, the `BETWEEN` operator contains boundary values. [left closed right closed interval]

If you want to exclude 15 and 35 years old, you should use the following condition:

WHERE age > 15 AND age < 35

 Analysis:

The command in SQL to modify the table structure is ALTER TABLE.

Use the ALTER TABLE command to add, modify, or delete columns from a table, as well as rename existing columns or change their data type.

For example, the following SQL statement adds a column birthdate to a table named t_student:

ALTER TABLE t_student ADD COLUMN birthdate DATE;

This statement uses the ALTER TABLE command and uses the ADD COLUMN clause to add a date type column named birthdate to the t_student table.

 Analysis:

In SQL, the command used to create a table is CREATE TABLE.

Through the CREATE TABLE command, we can define a new table structure and specify the name of the table, column names, data types, constraints and other information.

For example, the following is an example of using the CREATE TABLE command to create a table named t_users:

CREATE TABLE t_users (
    id INT,
    name VARCHAR(50),
    age INT,
    email VARCHAR(100)
);

This statement uses the CREATE TABLE command to create a table named t_users, which contains four columns: id, name, age, and email. The data types of each column are INT, VARCHAR, and INT respectively.

Analysis:

The default port number for the MySQL database is 3306.

MySQL is a popular relational database management system that uses the TCP/IP protocol for communication.

 Analysis:

A. A primary key is a field or combination of fields used to uniquely identify each record. In MySQL, a table can only have one primary key.

B. Primary key columns cannot contain NULL values.

C. The primary key value of each record cannot be repeated with other records.

D. If it is an integer, you can set automatic growth: In MySQL, a common practice is to set the primary key to an integer type (such as INT) and use the AUTO_INCREMENT attribute to make it automatically increment to generate a unique value.

It should be noted that although a table can only have one primary key, a joint primary key (a primary key composed of multiple columns) can be used to uniquely identify a record.

 Analysis:

In MySQL, the keyword of the primary key is PRIMARY KEY.

Through the PRIMARY KEY keyword, we can define one or more columns as the primary key of the table.

For example, the following is an example of using the PRIMARY KEY keyword to define a primary key when creating a table:

CREATE TABLE t_users (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(100)
);

This statement creates a table named t_users with the id column defined as the primary key.

The keyword NULL for option A does not exist;

The keyword KEY of option B is usually used for index creation;

The keyword DEFAULT of option C is used to set the default value of the column.

Analysis:

In MySQL, the storage type of the corresponding string is varchar.

Varchar is a variable-length character type used to store string data of variable length.

A. int: int is a data type used to store integers. It can store integer values ​​but is not suitable for storing string data.

B. date: date is the type used to store date data. It can store date values ​​of year, month, and day, but is not suitable for storing string data.

C. varchar: varchar is a variable-length character type. It can store string data containing letters, numbers, and special characters. A varchar needs to specify a maximum length when it is created, but the actual stored string length can be less than this length.

D. decimal: decimal is a data type used to store exact decimals (floating point numbers). It is suitable for storing numbers with fixed-point decimal places, not for storing string data.

 Analysis:

C. The primary key column must be unique and cannot be empty. The unique column can be empty.

In MySQL, primary key and unique constraints are mechanisms used to ensure the uniqueness of a column or column combination in a data table, but they have some differences.

A. The primary key column must not be empty, because the primary key is used to uniquely identify each record, and a null value cannot uniquely identify a record.

B. Unique columns require that the value of each record is unique and duplicate values ​​are not allowed. If you try to insert duplicate values ​​into a unique column, a unique constraint violation error will be thrown.

Analysis:

A. INSERT table name [(field list)] VALUES(value list)

The statement to correctly add a piece of data in MySQL usually uses the INSERT INTO statement.

Its basic syntax is as follows:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

A. This statement will insert a new record in the specified table. The field list can optionally specify the inserted column, and the value list is the corresponding value.

B. ADD is used to add new columns rather than insert records.

C. APPEND is not a keyword of MySQL and cannot be used to indicate inserting new records.

D. INCREASE is not a keyword of MySQL and cannot be used to indicate inserting new records.

 

Analysis:

A. +: Addition operator, used to add two numerical values.

B. -: Subtraction operator, used to subtract two values.

C. *: Multiplication operator, used to multiply two values.

D. /: Division operator, used to divide two numbers.

Therefore, option D - || is not a MySQL arithmetic operator, but an operator used for string concatenation.

 Analysis:

In MySQL, the following are common MySQL comparison operators:

A. =: Equal operator, used to determine whether two values ​​are equal.

C. <>: Not equal to operator, used to determine whether two values ​​are not equal.

D. !=: MySQL comparison operator.

Therefore option B == is not a MySQL comparison operator. A single equal sign (=) should be used for equality comparisons in MySQL.

 Analysis:

A. CONCAT

In MySQL, use the `CONCAT` function to concatenate strings. The function can accept multiple parameters and concatenate them together according to the order of parameters.

B. LEFT(str, len)

The `LEFT` function is used to obtain the substring of a specified length on the left side of a string. It requires two parameters: one is the string itself, and the other is the length of the substring to be obtained.

C.PI()

The `PI` function returns an approximate value of pi.

D. LOWER(str)

The `LOWER` function is used to convert characters in a string to lowercase.

 Analysis:

In MySQL, you can use ORDER BY and GROUP BY at the same time in the query statement, but their order is limited. The correct order is to first use GROUP BY to group the results, and then use ORDER BY to sort the grouped data.

 Analysis:

In MySQL, results are grouped using the GROUP BY statement, and aggregate functions can be used to perform calculations on each group. When the MAX aggregate function is used in a GROUP BY statement, it returns the maximum value of the specified field in each grouping.

Option A is incorrect because the MAX aggregate function returns the maximum value in each grouping.

Option C is wrong. The grouping field and the MAX aggregation field do not need to be consistent and can be selected according to specific needs.

 Analysis:

When two tables are multiplied together, the number of rows in the result is equal to the product of the number of rows in the two tables, and the number of columns is equal to the sum of the number of columns in the two tables.

Given a table with 3 rows and 2 columns and a table with 3 rows and 4 columns, the result of multiplying them will be a resulting table with 9 rows and 6 columns.

Therefore, option D - 9 rows and 6 columns is correct.

 Analysis:

The aggregate function AVG is used in MySQL to calculate the average of a specified column.

Therefore, Option D - Average AVG function will return the average of all values ​​of a given column.

Analysis:

In MySQL, the keyword for filtering after user grouping is "HAVING".

The GROUP BY statement is used to group results by specified columns. However, if you need to filter the grouped results, you can use the HAVING keyword. The HAVING keyword is similar to the WHERE keyword, but it is a filter condition for grouped results.

Therefore, option D "HAVING" is the correct keyword for filtering after grouping.

Analysis:

A unique index is an index type used to ensure that the values ​​in the index columns are unique, that is, each index value can only correspond to one record. Using a unique index can effectively avoid duplicate data.

Option A - fulltext is the keyword used for full-text indexing.

Option B - only is not a keyword used for unique indexes in MySQL.

Option D - index is the keyword used to create the index.

Therefore, option C - unique is the correct keyword to use to define a unique index.

 Analysis:

A. Read Uncommitted: All transactions can see the execution results of other uncommitted transactions. Generally, the performance of this isolation level is relatively low.

B. Read Committed (read committed content): It is the default isolation level of most databases (excluding Mysql). An ongoing transaction can see changes made by committed transactions. The same search statement may have different return results because other transactions may have completed changes to the data during the execution of other instances of the same transaction.

C. Repeated Read: Mysql uses this isolation level by default, which ensures that the same transaction sees the same data when different instances read data concurrently. However, a "phantom read" situation will occur, that is, during the execution of the transaction, another transaction inserts a new piece of data within its scope, resulting in two instances of the same transaction displaying different data for the same query. InnoDB and Falcon storage engines solve this problem through multi-version concurrency control, which seems to prevent insertion by adding gap locks, but it may also lead to deadlock.

D. Serializable (serializable): This is the highest level of isolation. It solves the problem of phantom reads by forcing transactions to be sorted, making it impossible to conflict. It is implemented by adding a shared lock to each data row. . But it will cause a lot of timeouts.

 Analysis:

MySQL ensures that data will not be lost by using "redo log" and "binlog".

Option A - The redo log is MySQL's transaction log, which records modifications to the database. When MySQL executes a transaction, it first writes the modifications to the redo log and then applies them to the data files on disk. This ensures that even in the event of a system crash or power outage, MySQL can recover data by replaying operations in the redo log, thereby avoiding data loss.

Option C - binlog (binary log) is MySQL's binary log file, which records all change operations made to the database, including data modification statements and data definition statements. Binlog can be used for data backup, data replication and fault recovery. In the case of master-slave replication, the master database will record modification operations to the binlog, and then the slave database will synchronously update the data based on the binlog to achieve data replication.

Therefore, option D - redo log+binlog is the correct answer. MySQL ensures the durability and recoverability of data by using both redo log and binlog to avoid data loss to the greatest extent.

 Analysis:

Transactions have four characteristics, namely atomicity, consistency, isolation and durability.

A. Atomicity: Transactions are regarded as an indivisible minimum unit, and either all are successfully executed or all are rolled back to the initial state. That is, all operations of the transaction are either completed and the results are permanently saved, or none are executed and cannot be partially executed.

B. Consistency: The integrity constraints of the database are not violated before and after the transaction is executed. The execution of a transaction should move the database from one consistency state to another.

C. Isolation: When multiple transactions are executed concurrently, each transaction feels like it is operating data independently without interfering with each other. Isolation prevents data races and inconsistencies between concurrent transactions.

D. Durability: Once a transaction is committed, its results should be permanent, and data durability should be guaranteed even if the system fails.

Therefore, option E - Recurrence is not a characteristic of transactions. The four characteristics of transactions are atomicity, consistency, isolation, and durability.

 Analysis:

MySQL's Server layer mainly includes the following functions:

A. Connector (Connection Manager): The connector is responsible for handling the connection management between the client and the database. It accepts the client's connection request, verifies identity, permissions and passwords, and creates the corresponding session.

B. Query Cache: In MySQL version 8.0 and before, MySQL provides a query cache function for caching query results to speed up the response to the same query. However, due to issues such as lock competition caused by caching, the query cache has been abandoned since MySQL version 8.0.

C. Parser: The parser is responsible for parsing SQL statements and converting them into internal data structures for subsequent processing. It detects syntax errors in SQL statements and generates corresponding syntax trees.

D. Optimizer: The optimizer is responsible for optimizing the analyzed SQL statements to improve query performance. It will consider multiple execution plans, select the optimal execution plan, and generate the corresponding execution plan tree.

E. Executor: The executor is responsible for executing the specific operations of the query statement. It reads data from the storage engine and returns the results to the client according to the execution plan tree generated by the optimizer. The executor is also responsible for handling operations such as transaction commit and rollback.

These functions form the core part of the MySQL Server layer, which is responsible for handling connection management with clients, SQL statement parsing, query optimization and execution processes.

Analysis:

mistake. In MySQL, creating an index can indeed improve query efficiency, but it does not mean that as long as the index is created, the query will be able to use it. Here are some situations that may affect index usage:

  1. Query conditions do not match: If the query conditions do not match the index columns, MySQL may not be able to use the created index. For example, if a table's primary key is ida column and your query condition is name='John', MySQL may not use idthe column's index because it does not match the query condition.
  2. Index selectivity is not enough: The selectivity of the index refers to the ratio of the value of the index column relative to the total number of rows in the table. If the values ​​of the index column are very concentrated, the selectivity is very high, otherwise the selectivity is very low. When a column in a query condition is not selective enough, MySQL may not use the index for that column.
  3. Index conflict: If there are multiple indexes in the table, and the query conditions involve multiple index columns, MySQL may choose to use one of the indexes instead of the others. This is because in some cases, using different indexes may give the same results but consume different resources.
  4. Query optimizer decision: MySQL's query optimizer will decide whether to use an index based on factors such as query complexity, index selectivity, and the number of rows in the table. Sometimes, although an index is available, the optimizer may choose a full table scan instead of using the index to avoid additional disk I/O overhead.

Therefore, although creating an index can improve query efficiency, it does not mean that as long as the index is created, the query will definitely be able to use it. Correct index design and optimization strategies need to consider factors such as table structure, query frequency and complexity, data distribution, etc., in order to improve query performance and efficiency.

 Analysis:

correct. MySQL uses multi-version concurrency control (MVCC, Mutil-Version Concurrency Control) to achieve repeatable reads.

In MVCC, each transaction will obtain a unique transaction ID (called a "version number") at the beginning, which will be associated with all database modification operations performed by the transaction. When other transactions try to read these modifications, they see the database version associated with their own transaction ID, not the current transaction's version. This way, each transaction can work on its own version without interfering with other concurrent transactions.

When a transaction ends and commits, its transaction ID is released so that other transactions can access the latest database version. If a transaction is not committed throughout its lifetime, then when it ends, all modifications will be rolled back to maintain database consistency.

This concurrency control mechanism allows isolation levels to be implemented between concurrently executing transactions, providing consistency guarantees for repeatable reads. For example, in a repeatable read transaction, even if other concurrent transactions are performing modification operations, the transaction can execute queries on its own read version to ensure that the read data is consistent.

The InnoDB storage engine in MySQL uses MVCC to implement transaction concurrency control and consistency guarantee.

 Analysis:

Error . MySQL's repeatable read level cannot completely solve the problem of phantom read (Phantom Read).

Among MySQL's transaction isolation levels, Repeatable Read is one of the levels, which provides certain concurrency control and data consistency guarantees. At the repeatable read level, the data seen by a transaction during execution is consistent and will not be affected by other transactions. This also means that reading the same row of data multiple times within the same transaction will yield the same result.

However, phantom read (Phantom Read) is one of the problems that cannot be solved by the repeatable read level in the MySQL transaction isolation level. Phantom reading means that during the execution of a transaction, due to the modification operations of other transactions, reading the same row of data multiple times in the same transaction may result in different results. This situation usually occurs when there are multiple transactions modifying the data row at the same time.

In order to solve the problem of phantom reads, MySQL provides another transaction isolation level - Serializable level. The serializability level can ensure that there is no interference between concurrently executed transactions, and data consistency can be fully guaranteed, but this also means that concurrency performance will be affected.

Therefore, although MySQL's repeatable read level can solve some problems of concurrency control and data consistency, it is not a panacea, and there are still some unsolvable problems, such as phantom reads.

 Analysis:

Correct . MySQL's auto-incrementing primary key is usually continuous.

In MySQL, if you define an auto-incrementing primary key for a table (for example, using AUTO_INCREMENTan attribute), MySQL automatically assigns each newly inserted row a unique identifier greater than the maximum value. This identifier is usually consecutive because MySQL internally uses a counter to keep track of the next available increment value.

However, it should be noted that the continuity of auto-incrementing primary keys is not absolutely guaranteed. Discontinuous auto-increment primary key values ​​may occur under certain circumstances, such as when a transaction rolls back or when an auto-increment primary key reaches its maximum value and the cycle starts again.

In addition, if you set AUTO_INCREMENT_INCREMENTand AUTO_INCREMENT_OFFSETsystem variables, the way the auto-incrementing primary key is generated will also be affected, and continuity may not be guaranteed.

In short, under normal circumstances, MySQL's auto-incrementing primary key is continuous, but in some specific cases, discontinuity may occur.

Guess you like

Origin blog.csdn.net/qq_53142796/article/details/132761250