The 2020 Java interview questions summarize the high-frequency interview questions of the mysql series (50 questions with answers)

During this period of time, I collected Java interview questions from companies such as Ali, Tencent, Baidu, Jingdong, Meituan, and ByteDance, and summarized the high-frequency interview questions of the mysql series:

premise

Some interview questions collected in the latest 2020 (all organized into documents), there are a lot of dry goods, including detailed explanations of mysql, netty, spring, thread, spring cloud, etc., there are also detailed study plans, interview questions, etc. I feel that I am in the interview This section is very clear: to get the interview information, just: click here to get it!!! Password: CSDNInsert picture description here

1. What kinds of locks are there in MySQL?

(1) Table-level locks: low overhead, fast locking; no deadlocks; large locking granularity, the highest probability of lock conflicts, and the lowest concurrency.
(2) Row-level locks: high overhead and slow locking; deadlocks will occur; the lock granularity is the smallest, the probability of lock conflicts is the lowest, and the concurrency is the highest.
(3) Page locks: The overhead and lock time are between table locks and row locks; deadlocks will occur; lock granularity is between table locks and row locks, and the concurrency is average.

2. What are the different tables in MySQL?

There are 5 types of tables:
(1) MyISAM
(2) Heap
(3) Merge
(4) INNODB
(5) ISAM

3. Briefly describe the difference between MyISAM and InnoDB in the MySQL database

MyISAM:
(1) does not support transactions, but each query is atomic;
(2) supports table-level locking, that is, each operation locks the entire table;
(3) stores the total number of rows in the table;
(4) one MYISAM table has three files: index file, table structure file, data file;
(5) Philippine clustered index is adopted, and the data field of the index file stores the pointer to the data file. The auxiliary index is basically the same as the main index, but the uniqueness of the auxiliary index is not guaranteed.
InnoDb:
(1) Supports ACID transactions and supports four isolation levels of transactions;
(2) Supports row-level locks and foreign key constraints: therefore can support write concurrency;
(3) Does not store the total number of rows:
(4) An InnoDb engine Stored in one file space (shared table space, table size is not controlled by the operating system, one table may be distributed in multiple files), or multiple (set to independent table space, table size is limited by the operating system file size, Generally 2G), limited by the file size of the operating system;
(5) The primary key index uses a clustered index (the data field of the index stores the data file itself), and the data field of the secondary index stores the value of the primary key; therefore, you need to look up data from the secondary index First find the primary key value through the secondary index, and then access the secondary index; it is best to use the self-incrementing primary key to prevent data insertion, in order to maintain the B+ tree structure, the file is adjusted.

4. The names of the four transaction isolation levels supported by InnoDB in MySQL, and the difference between each level? The four isolation levels defined by the SQL standard are:

(1) read uncommited: read uncommitted data
(2) read committed: dirty read, non-repeatable read

(3) repeatable read: rereadable
(4) serializable: serial things

5. What is the difference between CHAR and VARCHAR?

(1) CHAR and VARCHAR types are different in storage and retrieval

(2) The length of the CHAR column is fixed to the length declared when the table is created. The length value range is 1 to 255. When CHAR values ​​are stored, they are padded with spaces to a specific length. When retrieving CHAR values, trailing spaces need to be deleted.

6. What is the difference between primary key and candidate key?

Each row of the table is uniquely identified by the primary key, and a table has only one primary key.
The primary key is also a candidate key. By convention, candidate keys can be designated as primary keys and can be used for any foreign key references.

7. What is myisamchk used for?

It is used to compress MyISAM tables, which reduces disk or memory usage.
What is the difference between MyISAM Static and MyISAM Dynamic?

All fields on MyISAM Static have a fixed width. The dynamic MyISAM table will have fields like TEXT, BLOB, etc. to accommodate data types of different lengths.
MyISAM Static is easier to recover in case of damage.

8. If a table has a column defined as TIMESTAMP, what will happen?

Whenever the row is changed, the timestamp field will get the current timestamp.

When the column is set to AUTO INCREMENT, what happens if it reaches the maximum value in the table?
It will stop incrementing, and any further insertion will generate an error because the key has already been used.
How can I find out which auto increment was assigned during the last insert?

LAST_INSERT_ID will return the last value assigned by Auto_increment, and there is no need to specify the table name.

9. How do you see all the indexes defined for the table?

The index is defined for the table in the following way:
SHOW INDEX FROM;

10. What do% and _ in the LIKE statement mean?

% Corresponds to 0 or more characters, _ is just one character in the LIKE statement.

How to convert between Unix and MySQL timestamps?
UNIX_TIMESTAMP is the command to convert from MySQL timestamp to Unix timestamp

FROM_UNIXTIME is the command to convert from Unix timestamp to MySQL timestamp

11. What is the column comparison operator?

Use =, <>, <=, <,> =, >, <<, >>, <=>, AND, OR or LIKE operators in the column comparison of the SELECT statement.

12. What is the difference between BLOB and TEXT?

BLOB is a binary object that can hold a variable amount of data. TEXT is a case-insensitive BLOB.

The only difference between BLOB and TEXT types is that BLOB values ​​are case-sensitive when sorting and comparing, and TEXT values ​​are not case-sensitive.

13. What is the difference between MySQL_fetch_array and MySQL_fetch_object?

The following are the differences between MySQL_fetch_array and MySQL_fetch_object:
MySQL_fetch_array() – returns the result row as an associative array or a regular array from the database.

MySQL_fetch_object – returns the result row from the database as an object.

14. Where will the MyISAM tables be stored and also provide their storage format?

Each MyISAM table is stored on the disk in three formats:
(1) ".frm" file storage table definition

(2) The data file has the extension ".MYD" (MYData)
(3) The index file has the extension ".MYI" (MYIndex)

15. How does MySQL optimize DISTINCT?

DISTINCT is converted to GROUP BY on all columns and used in conjunction with the ORDER BY clause.

SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a;

16. How to display the first 50 lines?

In MySQL, use the following code query to display the first 50 rows:
SELECT*FROM

LIMIT 0,50;

17. How many columns can be used to create an index?

Any standard table can create up to 16 index columns.

18. What is the difference between NOW() and CURRENT_DATE()?

The NOW() command is used to display the current year, month, date, hour, minute, and second.

CURRENT_DATE() only displays the current year, month and date.

19. What is a non-standard string type?

(1)TINYTEXT
(2)TEXT

(3)MEDIUMTEXT
(4)LONGTEXT

20. What is a general SQL function?

(1) CONCAT(A, B)-concatenate two string values ​​to create a single string output. Usually used to merge two or more fields into one field.

(2) FORMAT(X, D)- format the effective digits from X to D.
(3) CURRDATE(), CURRTIME()- returns the current date or time.

(4) NOW ()-returns the current date and time as a value.
(5) MONTH(), DAY(), YEAR(), WEEK(), WEEKDAY()-Extract the given data from the date value.

(6) HOUR(), MINUTE(), SECOND()-extract the given data from the time value.
(7) DATEDIFF (A, B)-Determine the difference between two dates, usually used to calculate age

(8) SUBTIMES (A, B)-Determine the difference between two times.
(9) FROMDAYS (INT)-Convert integer days to date values.

21. Does MySQL support transactions?

In the default mode, MySQL is in autocommit mode, and all database update operations will be committed immediately, so by default, MySQL does not support transactions.
But if your MySQL table type uses InnoDB Tables or BDB tables, your MySQL can use transaction processing. Use SETAUTOCOMMIT=0 to allow MySQL to be in non-autocommit mode. In non-autocommit mode, you must use COMMIT to Commit your changes, or use ROLLBACK to roll back your changes.

22. What field type is good for recording currency in MySQL

The NUMERIC and DECIMAL types are implemented by MySQL as the same type, which is allowed in the SQL92 standard. They are used to save values ​​whose accuracy is extremely important, such as data related to money. When declaring a class to be one of these types, the precision and scale can be (and usually is) specified.
E.g:

salary DECIMAL(9,2)
In this example, 9 (precision) represents the total number of decimal places that will be used to store the value, and 2 (scale) represents the number of decimal places that will be used to store the value.

Therefore, in this case, the range of values ​​that can be stored in the salary column is from -9999999.99 to 9999999.99.

23. What are the MySQL tables related to permissions?

The MySQL server controls the user's access to the database through the permission table. The permission table is stored in the MySQL database and initialized by the MySQL_install_db script. These privilege tables are user, db, table_priv, columns_priv and host respectively.

24. What can be the string type of the column?

The string type is:
(1) SET2

(2)BLOB
(3)ENUM

(4)CHAR
(5)TEXT

25. The MySQL database is used as the storage of the publishing system, with an increment of more than 50,000 entries per day. It is expected to operate and maintain for three years. How to optimize?

(1) Design a well-designed database structure, allow partial data redundancy, try to avoid join queries, and improve efficiency.
(2) Select the appropriate table field data type and storage engine, and add indexes appropriately.

(3) MySQL library master and slave read and write separation.
(4) Find regular sub-tables, reduce the amount of data in a single table and improve query speed.

(5) Add caching mechanisms, such as memcached, apc, etc.
(6) Generate static pages for pages that are not frequently changed.

(7) Writing efficient SQL. For example, SELECT * FROM TABEL is changed to SELECT field_1, field_2, field_3 FROM TABLE.

26, lock optimization strategy

(1) Read and write separation
(2) Segmented locking

(3) Reduce lock holding time
(4) Multiple threads try to acquire resources in the same order

The granularity of the lock cannot be too fine, otherwise there may be too many threads to lock and release, but the efficiency is not as good as adding one large lock at a time.

27. The underlying implementation principle and optimization of the index

B+ tree, optimized B+ tree
mainly adds a pointer to the next leaf node in all leaf nodes, so InnoDB recommends using the default auto-incremented primary key as the primary index for most tables.

28. Under what circumstances the index is set but cannot be used

(1) LIKE statements beginning with "%", fuzzy matching
(2) Indexes are not used before and after the OR statement

(3) Implicit conversion of data type (such as varchar without single quotes, it may be automatically converted to int type)

29. How to optimize MySQL in practice

It is best to optimize in the following order:
(1) Optimization of SQL statements and indexes

(2) Optimization of database table structure
(3) Optimization of system configuration

(4) Optimization of hardware

30. Methods to optimize the database

(1) Select the most applicable field attribute, reduce the width of the defined field as much as possible, and try to set the field as NOTNULL, such as'province','gender', preferably ENUM
(2) use JOIN instead of sub-query

(3) Apply union (UNION) instead of manually created temporary table
(4) Transaction processing

(5) Lock tables, optimize transaction processing
(6) Apply foreign keys, optimize lock tables

(7) Establish index
(8) Optimize query statement

31. Briefly describe the difference between index, primary key, unique index, and joint index in MySQL, and what impact it has on database performance (from both read and write)

Indexes are a special kind of files (indexes on InnoDB data tables are a part of the table space), they contain reference pointers to all records in the data table.

The only task of an ordinary index (an index defined by the keyword KEY or INDEX) is to speed up data access.
Ordinary indexes allow the indexed data column to contain duplicate values. If you can determine that a data column will only contain values ​​that are different from each other, you should use the keyword UNIQUE to define it as a unique index when creating an index for this data column. In other words, the unique index can guarantee the uniqueness of data records.
The primary key is a special unique index. Only one primary key index can be defined in a table. The primary key is used to uniquely identify a record and is created using the keyword PRIMARY KEY.
Indexes can cover multiple data columns, such as indexes like INDEX (columnA, columnB), which is a joint index.
Indexes can greatly improve the speed of data query, but will reduce the speed of inserting, deleting, and updating tables, because when performing these write operations, the index file must be operated.

32. What is the transaction in the database?

A transaction is a set of ordered database operations as a unit. If all operations in the group succeed, the transaction is considered successful, even if only one operation fails, the transaction is not successful. If all operations are completed, the transaction is committed, and its modifications will act on all other database processes. If an operation fails, the transaction will be rolled back and the impact of all operations of the transaction will be cancelled.
Transaction characteristics:

(1) Atomicity: Indivisibility, transactions are either all executed or not executed at all.
(2) Consistency or stringency. The execution of the transaction makes the database from one correct state to another correct state.
(3) Isolation. Before the transaction is committed correctly, it is not allowed to provide any data changes made by the transaction to any other transaction.
(4) Persistence. After the transaction is submitted correctly, the result will be permanently saved in the database. Even if there are other failures after the transaction is submitted, the processing result of the transaction will be saved.

Or understand this: A
transaction is a group of SQL statements that are bound together as a logical unit of work. If any statement operation fails, the entire operation will fail, and the operation will roll back to the state before the operation, or there is a node. To ensure that it is either executed or not executed, you can use transactions. To consider grouped statements as transactions, it is necessary to pass the ACID test, namely atomicity, consistency, isolation, and durability.

33. What causes SQL injection vulnerabilities? How to prevent it?

Reasons for SQL injection: In the process of program development, care is not taken to write sql statements and filter special characters. As a result, the client can submit some sql statements through global variables POST and GET for normal execution.

Ways to prevent SQL injection:
enable magic_quotes_gpc and magic_quotes_runtime settings in the configuration file

Use addslashes to convert SQL statements when executing SQL statements.
Try not to omit double quotes and single quotes when writing SQL statements.
Filter out some keywords in the sql statement: update, insert, delete, select, *.
Improve the naming skills of database tables and fields. Name some important fields according to the characteristics of the program, and choose the ones that are not easy to guess.

34. Select the appropriate data type for the fields in the table

Field type priority: integer>date,time>enum,char>varchar>blob,text
gives priority to numeric types, followed by date or binary types, and finally string types. Data types of the same level should be selected for smaller space Data type

35. Storage period

Datatime:
Store period time in YYYY-MM-DD HH:MM:SS format, accurate to the second, occupy 8 bytes of storage space, datatime type has nothing to do with time zone Timestamp: Store in timestamp format, occupy 4 bytes, The range is small from 1970-1-1 to 2038-1-19. The display depends on the specified time zone. By default, when the data in the first column and row is modified, the value of the timestamp column can be automatically modified.
Date:
(birthday) occupied bytes The number is less than the use of the string .datatime.int to store it. The use of date only requires 3 bytes to store the date and month. You can also use the date and time function to calculate the period of the day.
Time:
Store the time part of the data.
Note:
Do not use a string Type to store date and time data (usually occupies less storage space than a string, you can use the date function for searching and filtering)
using int to store date and time is not as good as using timestamp type

36. Indexes are a very important concept for relational databases. Please answer a few questions about indexes:

(1) What is the purpose of the index?
Quickly access the specific information in the data table and improve the retrieval speed.
Create a unique index to ensure the uniqueness of each row of data in the database table.
Speed ​​up the connection between tables and tables
When using grouping and sorting clauses for data retrieval, you can significantly reduce the time for grouping and sorting in queries

(2) What is the negative impact of indexes on the database system?
Negative impact: It
takes time to create and maintain indexes. This time increases as the amount of data increases; indexes need to take up physical space, not only tables need to take up data space, but each index also needs to take up physical space; Indexes should also be dynamically maintained when adding, deleting, modifying, and so on, which reduces the speed of data maintenance.
(3) What are the principles for indexing data tables?
Create indexes on the most frequently used fields to narrow the scope of the query.
Create an index on frequently used fields that need to be sorted
(4) Under what circumstances is it inappropriate to create an index?
For columns that are rarely involved in the query or columns with many duplicate values, it is not appropriate to create an index.
For some special data types, it is not appropriate to create indexes, such as text fields (text), etc.

37. Explain the difference between MySQL outer connection, inner connection and self connection

Let me talk about cross join first: Cross join is also called Cartesian product. It refers to directly matching all records in one table with all records in another table without using any conditions.
Inner joins
are only conditional cross joins. According to a certain condition, records that meet the conditions are filtered out. Records that do not meet the conditions will not appear in the result set, that is, inner joins only connect matching rows. The result set of
outer joins
not only contains rows that meet the join conditions, but also includes all data rows in the left table, right table, or both tables. These three cases are called left outer join, right outer join, and full External connection.
Left outer join is
also called left join. The left table is the main table. All records in the left table will appear in the result set. For those records that do not match in the right table, they still have to be displayed. The field values ​​corresponding to the right are NULL To fill. Right outer join, also called right join, the right table is the main table, and all the records in the right table will appear in the result set. Left connection and right connection can be interchanged, MySQL currently does not support full outer connections.

38. Overview of transaction rollback mechanism in Myql

A transaction is a user-defined sequence of database operations. These operations are either done or not done at all. It is an indivisible unit of work. Transaction rollback refers to undoing the update operation of the database that has been completed by the transaction.
When you want to modify two different tables in the database at the same time, if they are not a transaction, when the first table is modified, there may be an exception during the modification of the second table and it cannot be modified. At this time, there is only the second table It is still the state before the modification, and the first table has been modified. And when you set them as a transaction, when the first table is modified, and the second table is modified abnormally but cannot be modified, the first table and the second table must return to the unmodified state. This is the so-called transaction rollback

39. What parts does the SQL language include? What are the operational keywords in each part?

The SQL language includes four parts: data definition (DDL), data manipulation (DML), data control (DCL) and data query (DQL).
Data definition:
Create Table, Alter Table, Drop Table, Craete/Drop Index, etc.
Data manipulation:
Select, insert, update, delete,
data control:
grant, revoke
data query:
select

40. What are the integrity constraints?

Data Integrity (Data Integrity) refers to the accuracy (Accuracy) and reliability (Reliability) of data.
Divided into the following four categories:
(1) Entity integrity:
stipulate that each row of the table is the only entity in the table.
(2) Domain integrity:
It means that the columns in the table must meet a certain specific data type constraint, which includes the value range, precision and other provisions.
(3) Referential integrity:
It means that the data of the primary key and foreign key of the two tables should be consistent, ensuring the consistency of the data between the tables, and preventing data loss or meaningless data from spreading in the database.
(4) User-defined integrity:
Different relational database systems often require some special constraints according to their different application environments. User-defined integrity is the constraint condition for a particular relational database, and it reflects the semantic requirements that a specific application must meet.
Table-related constraints:
including column constraints (NOT NULL (non-null constraints)) and table constraints (PRIMARY KEY, foreign key, check, UNIQUE).

41. What is a lock?

The database is a shared resource used by multiple users. When multiple users access data concurrently, multiple transactions will simultaneously access the same data in the database. If the concurrent operation is not controlled, incorrect data may be read and stored, and the consistency of the database may be destroyed.
Locking is a very important technology to achieve database concurrency control. Before the transaction operates on a certain data object, it sends a request to the system and locks it. After the lock is locked, the transaction has certain control over the data object. Before the transaction releases the lock, other transactions cannot update the data object.
Basic lock types: locks include row-level locks and table-level locks

42. What is a view? What is a cursor?

A view is a virtual table that has the same functions as a physical table. You can add, modify, check, and manipulate the view. A view is usually a subset of rows or columns of one table or multiple tables. Modifications to the view do not affect the basic table. It makes it easier for us to obtain data, compared to multi-table query.
Cursor: It effectively processes the query result set as a unit. The cursor can be positioned on a specific row in the unit, and retrieve one or more rows from the current row in the result set. You can modify the current row of the result set. Cursors are generally not used, but they are very important when you need to process data one by one.

43. What is a stored procedure? What to call?

A stored procedure is a pre-compiled SQL statement. The advantage is that it allows a modular design, that is, it only needs to be created once and can be called multiple times in the program later. If a certain operation needs to execute SQL multiple times, using stored procedures is faster than pure SQL statement execution. You can use a command object to call a stored procedure.

44. How to understand the three paradigms in a popular way?

The first paradigm: 1NF atomic constraints on properties, required attribute is atomic, no longer decomposition;
second paradigm: 2NF is the only constraint records require unique identification is recorded, i.e., uniqueness of the entity;
Third Paradigm: 3NF is a constraint on the redundancy of fields, that is, any field cannot be derived from other fields. It requires no redundancy in the field. .
Advantages and disadvantages of paradigm design:

Advantages: Data redundancy can be reduced as much as possible, making updates fast and small in size.
Disadvantages: For queries, multiple tables are required to associate, reducing writing efficiency and increasing reading efficiency, and it is more difficult to optimize indexing. De
-normalization:

Advantages: can reduce table associations, and can better optimize indexing.
Disadvantages: data redundancy and data abnormality, data modification requires more cost

45. What is a basic table? What is a view?

The basic table is an independent table in itself, and a relationship corresponds to a table in SQL. A view is a table derived from one or several basic tables. The view itself is not stored independently in the database, it is a virtual table

46. ​​What are the advantages of views?

(1) Views can simplify user operations
(2) Views enable users to view the same data from multiple perspectives;
(3) Views provide a certain degree of logical independence for the database;
(4) Views can provide security protection for confidential data .

47. What does NULL mean?

NULL means UNKNOWN (unknown): it does not mean "" (empty string). Any comparison to the NULL value will produce a NULL value. You cannot compare any value with a NULL value, and logically hope to get an answer.
Use IS NULL to judge NULL

48. The difference between primary key, foreign key and index?

The difference between primary key, foreign key and index

definition:

Primary key-uniquely identifies a record, cannot be duplicated, and is not allowed to be empty.
Foreign key-the foreign key of a table is the primary key of another table. The foreign key can be duplicated, and it can be a null
index-the field is not duplicated value, but it may have a null
effect:

Primary key-used to ensure data integrity
Foreign key-used to establish contact with other tables used
index-is to improve the speed of query sorting
Number:
primary key-there can only be one primary key

Foreign key-a table can have multiple foreign keys
Index-a table can have multiple unique indexes

49. What can you use to ensure that the fields in the table only accept values ​​in a specific range?

Check limit, which is defined in the database table, is used to limit the value entered in the column.

Triggers can also be used to limit the acceptable values ​​of fields in database tables, but this approach requires triggers to be defined in the table, which may affect performance in some cases.

50. What are the methods to optimize SQL statements? (Choose a few)

(1) Where clause: The connection between where tables must be written before other Where conditions, and those conditions that can filter out the maximum number of records must be written at the end of the Where clause. HAVING at the end.
(2) Use EXISTS instead of IN, and NOT EXISTS instead of NOT IN.
(3) Avoid using calculations on the index column
(4) Avoid using IS NULL and IS NOT NULL on the index column
(5) Optimize the query, try to avoid full table scans, first consider the where and order by involved Create an index on the column.
(6) Try to avoid performing null value judgments on fields in the where clause, otherwise it will cause the engine to abandon the use of indexes and perform full table scans
(7) Try to avoid performing expression operations on fields in the where clause, which will Cause the engine to give up using the index and perform a full table scan

At last

Some interview questions collected in the latest 2020 (all organized into documents), there are a lot of dry goods, including detailed explanations of mysql, netty, spring, thread, spring cloud, etc., there are also detailed study plans, interview questions, etc. I feel that I am in the interview This section is very clear: to get the interview information, just: click here to get it!!! Password: CSDNInsert picture description here

Guess you like

Origin blog.csdn.net/a646705816/article/details/109290949