One thousand Java interview Zhenti finishing series: MySQL soul fifty ask, in the case of the interview is not afraid!

1, MySQL in which has several locks?

  1. Table-level lock: Small overhead, lock fast; not deadlock; lock large size, the probability of lock conflicts of the highest and lowest degree of concurrency.
  2. Row-level locking: large overhead, locking slow; there will be a deadlock; locking the smallest size, lowest probability of lock conflicts, have the highest degree of concurrency.
  3. Page lock: locking overhead and time boundaries between the table and row locks; there will be a deadlock; locking granularity boundary between the table and row locks, concurrency in general.

2. What are the different tables in MySQL have?

There are five types of forms:

  • MyISAM
  • Heap
  • Merge
  • INNODB
  • MONTHLY

3, outlining the difference in MyISAM and InnoDB MySQL database

MyISAM: it does not support transactions, but each time the query is atomic; supports table-level locking, that is, each operation is a lock on the entire table; number of rows in the table is stored; a MYISAM table has three files: an index file, the file table structure , data files; phenanthrene using a clustered index, the index file stored in the data field of a pointer to the data file. Secondary index and the main index basically the same, but not guaranteed to be unique secondary index.

InnoDb: support for ACID transactions, supports four transaction isolation level; supports row-level locking, and foreign key constraint: it can support concurrent write;

Do not store the number of lines: a InnoDb engine is stored in a file space (shared table space, table size regardless of the operating system controls, a table may be spread across multiple files), there may be more (provided as a separate table space, table size by the operating system file size limit, usually 2G), is limited by the size of the operating system files;

Primary key index with aggregation index (index data field stores data file itself), the value of secondary index data field stores the primary key; thus lookup data from secondary index, need to find the master key through the secondary index, and then access the secondary index; best use increment primary key, when inserted to prevent data, to maintain the B + tree structure, the major files

4, MySQL InnoDB support in four transaction isolation level name, and the differences between progressive?

SQL standard defines four isolation levels are:

  1. read uncommited: read uncommitted data
  2. read committed: dirty reads, non-repeatable read
  3. repeatable read: can reread
  4. serializable: Serial thing

5, the difference between CHAR and VARCHAR of?

  • CHAR and VARCHAR types differ in terms of storage and retrieval
  • CHAR column length is fixed length when creating the specified table, a length range from 1 to 255 when CHAR values ​​are stored, they are padded with spaces to a certain length, trailing spaces to be deleted CHAR values ​​are retrieved.

6, the primary key and candidate keys What is the difference?

Each line of the primary key that uniquely identifies the table, a table has only one primary key.

Primary key is a candidate key. Conventionally, the candidate keys may be designated as the primary key, and may be used for any foreign key references.

7, myisamchk what to do?

It is used to compress MyISAM tables, which reduces disk or memory usage.

MyISAM Static and MyISAM Dynamic What is the difference? All fields in MyISAM Static has a fixed width. MyISAM table having dynamic image TEXT, BLOB fields such as to accommodate different lengths of the data type. MyISAM Static easier recovery in case of damage.

8, if a table has a defined as TIMESTAMP, what will happen?

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

When the column is set to AUTO INCREMENT, if it reaches the maximum value in the table, what happens? It will stop increments, any further insertion will produce an error, because the key is already in use.

How can I find out the last time when you insert which is assigned automatically increment? LAST_INSERT_ID returns the last value assigned by Auto_increment, and need not specify the table name

9, how do you see that all indexes defined for the table?

The index is defined by the following table as a way of:

SHOW INDEX FROM <tablename>;
复制代码

10, LIKE declaration% and _ What does this mean?

Corresponds to 0% or more characters, a character just _ LIKE statement.

How to convert between Unix and MySQL timestamp?

  • UNIX_TIMESTAMP is converted from MySQL timestamp Unix timestamp command
  • FROM_UNIXTIME is converted from Unix timestamp for MySQL timestamp command

11. What comparison operator is the column?

SELECT statement used in the comparison column =, <>, <=, <,> =,>, <<, >>, <=>, AND, OR, or LIKE operator.

12, BLOB and TEXT What is the difference?

A BLOB is a binary object, you can hold a variable amount of data. TEXT BLOB is not case-sensitive.

The only difference between the BLOB and TEXT types is the sorting and BLOB values ​​case-sensitive comparison, the value of TEXT case insensitive.

13. What is the difference MySQL_fetch_array and MySQL_fetch_object is?

The following is the difference between MySQL_fetch_array and MySQL_fetch_object of:

  • MySQL_fetch_array () - the result as an associative array or a conventional line array returned from the database.
  • MySQL_fetch_object - return results from the database row as an object.

14, MyISAM tables will be where to store, and also provides its storage format?

Each MyISAM table is stored on disk in three formats:

  • · ".Frm" file stores the table
  • · Data file has ".MYD" (MYData) extension
  • Index files have ".MYI" (MYIndex) extension

15, MySQL how to optimize DISTINCT?

DISTINCT conversion on all columns GROUP BY, 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, using 50 lines of code before the following query is displayed:

SELECT*FROMLIMIT 0,50;
复制代码

17, how many columns you can use to create an index?

Any standard table can create up to 16 index column.

18, NOW () and CURRENT_DATE () What is the difference?

  • NOW () command is used to display the current year, month, date, hours, minutes and seconds.
  • CURRENT_DATE () displays only the current year, month and day.

19. What is a non-standard string type?

  1. TINYTEXT
  2. TEXT
  3. MEDIUMTEXT
  4. LONGTEXT

20, what is the generic SQL function?

  1. CONCAT (A, B) - connecting the two string values ​​to create a single output string. Typically for two or more fields into one field.
  2. FORMAT (X, D) - D format to a digital X-significant digits.
  3. CURRDATE (), CURRTIME () - Returns the current date or time.
  4. NOW () - the current date and time as a return value.
  5. MONTH (), DAY (), YEAR (), WEEK (), WEEKDAY () - date value extracted from the given data.
  6. HOUR (), MINUTE (), SECOND () - time value extracted from the given data.
  7. DATEDIFF (A, B) - determining the difference between the two dates, generally used to calculate the age of
  8. SUBTIMES (A, B) - determining the difference between the two.
  9. FROMDAYS (INT) - convert integer value date days.

21, MySQL support transactions do?

In the default mode, MySQL is autocommit mode, all database update operations will immediately submit, so by default, MySQL does not support transactions. But if your MySQL table types is to use InnoDB Tables or BDB tables, then your MySQL can use transaction processing, use SET AUTOCOMMIT = 0 can make MySQL allows a non-autocommit mode, in non-autocommit mode, you must use COMMIT to submit your changes, or use rOLLBACK to roll back your changes.

22, MySQL currency in record what type of field is good

MySQL NUMERIC and DECIMAL types are implemented as the same type, which allows SQL92 standard. They are used to hold values, the exact accuracy of the values ​​is extremely important values, such as data related to money. When a class is declared when 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) to be used on behalf of the total number of decimal places stored values, and 2 (scale) to be used on behalf of digits after the decimal point is stored. Thus, in this case, the range of values ​​that can be stored in the salary column is from -9999999.99 to 9,999,999.99.

23, Table MySQL related rights which has several?

MySQL server to control user access authority table by the database, permissions table stored in a MySQL database by MySQL_install_db initialization script. These rights are tables user, db, table_priv, columns_priv and host.

24, string type column can what is?

String types are:

  1. SET
  2. BLOB
  3. ENUM
  4. CHAR
  5. TEXT

25, MySQL database storage system for the release of more than fifty thousand one day increments, expected operation and maintenance for three years, how to optimize?

  1. A well-designed database structure that allows some data redundancy, avoid join queries and improve efficiency.
  2. Selecting the proper type of field data and storage engine, add the appropriate index.
  3. MySQL database separate from the main reader.
  4. Sub-table to find the law, reducing the amount of data in a single table to improve query speed.
  5. Added caching mechanism, such as memcached, apc and so on.
  6. Changes infrequently page, generate static pages.
  7. Writing efficient SQL. For example, SELECT * FROM TABEL changed SELECT field_1, field_2, field_3 FROM TABLE.

26, lock optimization strategy

  1. Separate read and write
  2. Locking segment
  3. Reducing the time the lock held
  4. Multiple threads in the same order as far as possible to acquire resources

We can not lock granularity is too refined, or may appear excessive locking and releasing the number of threads, but less efficient than one to add a big lock.

27, the underlying index principle and optimization

B + tree, B + tree optimized mainly to increased leaf node points to the next pointer at all leaf nodes, and therefore most of the recommendations for InnoDB table using the default auto-increment primary key as the primary index.

28. Under what circumstances set but can not use the index

  1. LIKE statement to "%" at the beginning, fuzzy matching
  2. OR before and after the statement has no index is used
  3. There is an implicit data type conversion (e.g. varchar without single quotation marks may then automatically converted to an int)

29, how to practice to optimize MySQL

Optimization is preferably in the following order:

  1. SQL optimization and indexing
  2. Optimize the structure of the database table
  3. System configuration optimization
  4. Hardware optimization

30. A method of optimizing database

  1. Select the most suitable field attribute definition field width to minimize, as far as possible field NOTNULL provided, for example, 'Department', 'Sex' best applicable ENUM
  2. Using the connection (the JOIN) instead subquery
  3. Apply to the United (UNION) instead of manually create the temporary table
  4. Transaction Processing
  5. Lock the table, optimized transaction processing
  6. Applicable foreign key, optimistic locking table
  7. Indexing
  8. Query optimization

31, a brief description MySQL, indexes, primary keys, unique indexes, joint index difference, have any effect on the performance of the database (from both read and write)

Is a special index file (index on InnoDB table is part of a table space), which contains pointers to all records of the reference data table.

General index (the index by the keyword KEY or INDEX defined) only task is to speed up access to data.

Ordinary index allows data to be indexed column contains duplicate values. If you can determine the data column will only contain a different value each other, when creating an index of the data for this column should be defined with the keyword UNIQUE to it as a unique index. In other words, the only index to ensure the uniqueness of the data can be recorded.

Primary key is a special unique index, only the definition of a primary key index on a table, the primary key uniquely identifies a record be created using the keywords PRIMARY KEY.

Index may cover a plurality of data columns, such as INDEX (columnA, columnB) index, which is the joint index.

Index can greatly improve query speed data, but will reduce the insert, delete, update, speedometer, because in the implementation of these write operations, but also to operate the index file.

32, what database transactions are?

Transaction (transaction) as an ordered set of a database operation unit. If all the operations group are successful, the transaction is considered successful, even if there is only one operation fails, the transaction is not successful. If all operation is completed, the transaction is committed, it will revise the role of all other database processes. If the operation fails, the transaction is rolled back, the impact of the firm has operations will be canceled.

Transaction characteristics:

  1. Atomicity: the indivisibility of the transaction either all executed or not executed on all.
  2. Or consistency of the string. Executing the transaction database so that the correct conversion from one state to another state correctly
  3. Isolation. Before the transaction correctly submitted, does not allow any changes to the transaction data available to any other matters,
  4. Persistence. After the transaction the right to submit the results will be permanently stored in the database, even with the other failures in the transaction is committed, the result of processing the transaction will be saved.

Or this way:

Transaction is to be bound together as a logical unit of work packets SQL statement, a statement, if any operation fails then the whole operation was a failure, after the operation will be rolled back to the state before the operation, or has the nodes. In order to ensure either executed or not executed, you can use the transaction. To have a group of statements considered as a transaction, we need to pass the ACID test, namely atomicity, consistency, isolation and durability.

33, SQL injection causes of vulnerability results? How to prevent?

The reason SQL injection produced: program development process, specification writing sql statements and do not pay attention to the special character filtering, leading to some of the client can submit a properly executed sql statement by the global variables POST and GET.

Prevent SQL injection methods:

Magic_quotes_gpc open the configuration file and use addslashes be converted Sql sql statement is executed sql statement written statement as not to omit double and single quotes magic_quotes_runtime settings. Sql statement to filter out some key words: update, insert, delete, select, *. Improve skills naming database tables and fields, some important fields based on the characteristics of the program name, take can not easily be guessed.

34, the data obtained have to select the appropriate field type table

Priority field types: plastic> date, time> enum, char> varchar> blob, text prioritize numeric type, followed by the date or binary type, and finally the string type, have the same level of data types, you should prefer the small footprint data types

35, the storage period

Datatime: in YYYY-MM-DD HH: MM: SS format during the storage time, accurate to the second, 8 bytes of available storage space, regardless of the time zone datatime type Timestamp: storing timestamp format, 4 bytes, 1970-1-1 to 2038-1-19 small range, depending on the designated display region too, must be amended automatically default timestamp column Found Date :( birthday) modifying data in the first column of a row of bytes occupied obtained than the number string stored .datatime.int less, using only three bytes of date, day of the month is stored, can be calculated to obtain the date time date time functions: storage time section to obtain data NOTE: Do not use string date and time to store the type of data (usually occupy less than the available storage space of the string, filtration may be performed using a lookup function to obtain date) stores the date and time using the int is better to use the timestamp type

36, for the relational database index is a very important concept, please answer a few questions about indexes:

1. What is the purpose of the index? Quick access to data in the table specific information, to improve the retrieval speed to create a unique index to ensure the uniqueness of each row of data in a database table. When using the packet and the connection between the accelerometers and the sorting table clause data retrieval, a query can significantly reduce the time and packet ordering

2, any negative impact on the index is a database system? Negative effects: create indexes and index maintenance takes time, this time with the increase in the amount of data increases; the index needs to take up physical space, not just the data tables need to occupy space, each index also need to take up physical space; when the table add, delete, change, when the index should be dynamic maintenance, thus reducing the speed of data maintenance.

3, the principle of indexing the data table what? In the index on the field to narrow your search of the most frequently used. In the index, the need to sort frequently used fields

4, under what circumstances should not be indexed?

For the columns in the query rarely involved in repeat or more of the value of the column, not indexed. For some special data types, not indexed, such as a text field (text), etc.

37, explanation MySQL external connection, connected to the difference between the self-connected

Let me talk about what is the cross-connect: cross-connect also known as Cartesian product, it means without any conditions, directly to all records and all records of a table to another table in eleven matches.

En is the only cross-connect conditions, screened matching records based on some conditions do not meet the conditions of the record does not appear in the result set, that is, the connecting line only connects the match.

As a result, the outer connection lines that focus not only meet the connection conditions, but also includes all data rows from the left table, right table or two tables, called the three cases in turn connected to the left outer, right outer joins, and full outer joins.

Left outer join, also known as left connection, left the table the primary table, all records will be left of the table appear in the result set, for those records in the right table does not match, still have to show that those field values ​​corresponding to the right NULL to fill.

Right outer join, also known as the right connection, the right table the primary table, all records in the right table in the result set. Left and right connections are interchangeable, MySQL currently does not support full outer joins.

38, in a transaction rollback mechanism Myql Overview

A transaction is a sequence of user-defined database operations, these operations are either full or do not do the whole, an indivisible unit of work, transaction rollback means that the transaction has completed an update operation of the database revoked. To modify the database at the same time two different tables, if they are not a transaction, so that when the first table complete modification, there may be a second table to modify the course of abnormalities did not modify, then only the second table still unmodified state before, and the first table has been modified completed. And when you put them set a transaction time, when you modify the first table, the second table to modify abnormal and could not amend, the first table and the second table should be returned unmodified state, this is called transaction rollback

39, SQL language, including what parts? Each section has what action keywords?

Including SQL data definition language (DDL), data manipulation (DML), control data (DCL), and data query (DQL) four parts.

  • Data Definition: Create Table, Alter Table, Drop Table, Craete / Drop Index etc.
  • Data manipulation: Select, insert, update, delete,
  • Control data: grant, revoke
  • Data query: select

40, integrity constraints, including what?

Data integrity (Data Integrity) refers to the data precision (the Accuracy) and reliability (Reliability).

Divided into the following four categories:

  1. Entity integrity: each row in the table specified in the table is the only entity.
  2. Domain integrity: refers to the table column must satisfy a specific data type constraint, and wherein the constraint comprises a predetermined range, accuracy.
  3. Referential integrity: refers to two main data tables of keywords and the keyword should be consistent outside, to ensure consistency between the data tables, data loss or prevent diffusion of meaningless data in the database.
  4. User-defined integrity: different relational database systems, depending on their application environment, often also need some special constraints. User-defined integrity constraint that is for a particular relational database, which reflects the requirements of a specific application semantics must be met. Constraints associated with a table: including column constraints (NOT NULL (non-empty constraint)) and table constraints (PRIMARY KEY, foreign key, checkUNIQUE).

41, what is the lock?

The database is a shared resource used by more than one user. When multiple users concurrently accessing the data, it will have a plurality of transactions simultaneously access the same data in the database. If uncontrolled concurrent operations that could read and store incorrect data, break the consistency of the database.

Locking is a very important technology for database concurrency control. When a transaction before operating on a data object request Xianxiang system, its lock. Services on the data objects have some control after the lock, the lock is released prior to the transaction, no other transaction can update this data object. Basic types of locks: the lock comprises a row-level locks and table-level lock

42, what is the view? What cursors are?

A view is a virtual table, has the same functionality as a physical table. View may be made to add, change, check, operate, there is usually a view of a table or a subset of the plurality of rows or columns of the table. Changes to the view do not affect the basic table. It allows us to obtain data more easily, compared to multi-table queries. Cursor: as a means to effectively process the query result set out. The cursor can be set in a particular cell line, the current line retrieve one or more rows from the result set. You can make changes to the current row result set. Generally do not use a cursor, but need to process the data one by one when the cursor is very important.

43, what is stored procedure? To call what?

A stored procedure is a precompiled SQL statement, the advantage of allowing a modular design that is created once, later in the program can call multiple times. If you need to do many times a particular SQL, stored procedures using simple SQL statement is executed faster than that. You can use a command object to call a stored procedure.

44, how popular understanding of the three paradigms?

  • The first paradigm: 1NF atomic constraints on properties, required attribute is atomic, no longer decomposition;
  • The second paradigm: 2NF is the only constraint records require unique identification is recorded, i.e., uniqueness of the entity;
  • The third paradigm: 3NF field redundancy is bound to, that any field can not be derived from the other fields, it requires no redundant field. .

Paradigm design disadvantages: Advantages: the data redundancy can be reduced as much as possible to obtain such updated quickly, small drawbacks: the need for the query associated with a plurality of tables, reducing the efficiency of read write efficiency increases, more difficult to optimize the index

Anti paradigm: Advantages: reduced table may have associated index optimized to obtain better disadvantages: redundant data and abnormal data, the data must be amended more costly

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

Base table is a table itself is independent of the presence, in a SQL table a correspondence relations. Views are derived from one or several basic Table. View itself is not stored in the database independent, it is a virtual table

46, Shishu view of the advantages?

(1) can be simplified view of the operation of the user (2) enables the user to view the same data in a plurality of view angles; (3) provides a view of a degree of independence of the logical database; (4) a view to provide security protection for confidential data .

47, NULL What does it mean

This NULL value indicates that UNKNOWN (unknown): It does not mean, "" (the empty string). This value is NULL for any comparison will produce a NULL value. You can not put any value to a NULL value, and hope to get an answer on logic. Use IS NULL NULL be determined

48, the difference between primary keys, foreign keys and indexes?

definition:

  • Primary key - that uniquely identifies a record, can not be duplicated, NOT NULL
  • Foreign key - foreign key table is the primary key of another table, there may be repeated foreign key may be null
  • Index - This field value is not repeated, but can have a null value

effect:

  • Primary key - is used to ensure data integrity
  • Foreign keys - and to establish links with other tables
  • Index - is sort of improve query speed

Number:

  • Primary key - primary key can be only one
  • Foreign key - a table can have multiple foreign keys
  • Index - a table can have multiple unique index

49, what you can use to ensure that the form fields will only accept certain range in value?

Check limit, which is defined in a database table, for limiting the value of the input column. Triggers can also be used to limit the field in the database table to accept the values, but this approach requires a trigger is defined in the table, which may affect performance in some cases.

50, there is talk about what methods of optimizing SQL statements? (Select few)

  1. Where clause: where the connection between the tables must be written before other Where conditions, those conditions can filter out the maximum number of records to be written at the end of last .HAVING Where clause.
  2. Alternatively IN with EXISTS, NOT IN alternatively by NOT EXISTS. 3, avoid the use of columns in the index calculation
  3. Avoid the use of IS NULL and IS NOT NULL index columns
  4. Query optimization, should try to avoid full table scan, should first consider indexing by the column involved in where and order.
  5. Should be avoided fields null value judgment in the where clause, will cause the engine to give up using the index and full table scan
  6. Should be avoided fields operations expression in the where clause, which would cause the engine to give up using the index and full table scan

Guess you like

Origin juejin.im/post/5ddce5915188256eec6d7545