search
HomeDatabaseMysql TutorialSummarize knowledge related to Mysql

Summarize knowledge related to Mysql

Jun 21, 2017 pm 04:08 PM
mysqlstudynotes

Get database and table information

Generally normal programmers or DBAs will suddenly think of a series of questions like this when typing code: Who am I? Where am I? What am I doing? Where is my database? Where is my table? How did I create my table? What should I do? You might think of the SHOW DATABASES; command. But, this command is to list the databases managed by mysql. It is not a command to know where I am. Which command is it?

I found this command while browsing ancient classics:

SELECT DATABASE();

mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+----------- -+
| test |
+------------+
1 row in set (0.00 sec)

mysql>

Obviously, this is a command that tells me which database I am in. Then there will definitely be a group of young people asking: If I don’t enter any database, what will be displayed?

mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+-------- ----+
| NULL |
+------------+
1 row in set (0.00 sec)

mysql>

Of course it is NULL, what else can it be?

Now, we find the database (test) we are using. Then, it's time to find the table you're looking for, such as (pet). According to the records in ancient books, you should use the following command:

SHOW TABLES;

mysql> SHOW TABLES;
+--------------- -+
| Tables_in_test |
+----------------+
| event |
| pet |
+----- -----------+
2 rows in set (0.00 sec)

mysql>

And then I want to know the structure of the table. What should I do?

DESCRIBE pet;

mysql> DESCRIBE pet;
+---------+----------- --+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+--------- +-------+
| name | varchar(20) | YES | | NULL |
| owner | varchar(20) | YES | (20) | YES | | NULL | sex | char(1) | YES | | NULL | birth | date | YES | NULL date | YES | | NULL |
+---------+-------------+------+-----+---- -----+-------+
6 rows in set (0.00 sec)

mysql>

Old drivers are generally abbreviated as

DESC pet;

Field indicates the column name

Type indicates the data type of the column

Null indicates whether it can be NULL

Key indicates whether it is indexed

Default indicates the default value of the field

If the table has an index, SHOW INDEX FROM tbl_name displays the index information.

Examples of common queries

Before doing anything, you must first build one Table: Suppose there is a table (shop) to store the price () of each item () from a merchant (). (Items and merchants are used as primary keys)

The operation is as follows:

mysql> CREATE TABLE shop(

-> article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,

-> dealer CHAR(20) DEFAULT '' NOT NULL,

-> price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,

-> PRIMARY KEY(article, dealer));
Query OK, 0 rows affected (0.56 sec)

mysql>

Then insert some data:

mysql> INSERT INTO shop VALUES

-> (1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),

-> (3,' C',1.69),(3,'D',1.25),(4,'D',19.95);

Query OK, 7 rows affected (0.24 sec)

Records: 7 Duplicates: 0 Warnings: 0

mysql>

Check the table:

mysql> SELECT * FROM shop;
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0001 | A | 3.45 |
| 0001 | B | 3.99 |
| 0002 | A | 10.99 |
| B | 1.45 |
| 0003 | C | 1.69 |
| 0003 | D | 1.25 |
| 0004 | D | 19.95 |
+---------+--------+-------+
7 rows in set (0.00 sec)

mysql>

Then we can learn the following content


Maximum value of column

Example: What is the largest item number in the shop?

The operation is as follows:

SELECT MAX(article) FROM shop;

mysql> SELECT MAX(article) FROM shop;
+------ -------+
| MAX(article) |
+--------------+
| 4 |
+---- ----------+
1 row in set (0.00 sec)

mysql>

Example: To find the most expensive product

, do as follows:

SELECT MAX(price) FROM shop;

mysql> SELECT MAX(price) FROM shop;
+-- ----------+
| MAX(price) |
+------------+
| 19.95 |
+--- ---------+
1 row in set (0.00 sec)

mysql>

You know what the MAX() function does?

The row with the maximum value of a column

Chestnut: Query the most expensive Product information

The operation is as follows:

SELECT * FROM shop WHERE price = (SELECT MAX(price) FROM shop);

mysql> SELECT * FROM shop
-> WHERE price =
-> (SELECT MAX(price) FROM shop);
+---------+--------+---- ---+
| article | dealer | price |
+---------+--------+-------+
| 0004 | D | 19.95 |
+---------+--------+-------+
1 row in set (0.00 sec)

mysql>

There is another operation:

SELECT * FROM shop ORDER BY price DESC LIMIT 1;

mysql> SELECT * FROM shop
-> ; ORDER BY price DESC
-> LIMIT 1;
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0004 | D | 19.95 |
+ ---------+--------+-------+
1 row in set (0.00 sec)

mysql>

The former is a nested query, and the latter only displays one based on price sorting.

Maximum value of column: by group

Chestnut: each item (article )?

The operation is as follows:

SELECT article, MAX(price) AS price FROM shop GROUP BY article;

mysql> SELECT article, MAX( price) AS price
-> FROM shop
-> GROUP BY article;
+---------+-------+
| article | price |
+---------+-------+
| 0001 | 3.99 |
| 0002 | 10.99 |
| 0003 | 1.69 |
| 0004 | 19.95 |
+---------+-------+
4 rows in set (0.00 sec)

mysql>

The row with the maximum inter-group value of a certain field

I don’t understand what the title is mean. . . .

Chestnut: For each item, find the dealer of the most expensive item.

The operation is as follows:

SELECT article, dealer, price
FROM shop s1
WHERE price = (SELECT MAX(price)
FROM shop s2
WHERE s1 .article = s2.article);

mysql> SELECT article, dealer, price
-> FROM shop s1
-> WHERE price = (SELECT MAX(s2.price)
-> FROM shop s2
-> WHERE s1.article = s2.article);
+---------+--------+---- ---+
| article | dealer | price |
+---------+--------+-------+
| 0001 | B | 3.99 |
| 0002 | A | 10.99 |
| 0003 | C | 1.69 |
| 0004 | D | 19.95 |
+---------+- -------+-------+
4 rows in set (0.00 sec)

The book doesn’t explain why, and I don’t quite understand it either. Those who want to know more can explain in the comment area●﹏●.

Using user variables

Chestnut: Find the item with the highest or lowest price

The operation is as follows:

SELECT @min_price:=MIN(price), @max_price:=MAX(price) FORM shop;

SELECT * FROM shop WHERE price = @min_price OR price = @max_price;

mysql> SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;
+-------------------------- ----+------------------------+
| @min_price:=MIN(price) | @max_price:=MAX(price ) |
+------------------------+------------------- -----+
| 1.25 | 19.95 |
+--------------------------+------ ------------------+
1 row in set (0.13 sec)

mysql> SELECT * FROM shop WHERE price=@min_price OR price = @ max_price;
+---------+--------+-------+
| article | dealer | price |
+--- ------+--------+-------+
| 0003 | D | 1.25 |
| 0004 | D | 19.95 |
+-- -------+--------+-------+
2 rows in set (0.09 sec)

mysql>

There will be more information about user variables later, curious bustards can Baidu.

Use foreign keys

If you don’t want to do the operation directly, there is a transmission above Door, that’s very good.

CREATE TABLE person (
    id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name CHAR(60) NOT NULL,
    PRIMARY KEY (id)
);
 <br>
CREATE TABLE shirt (
    id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
    color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
    owner SMALLINT UNSIGNED NOT NULL REFERENCES person(id),
    PRIMARY KEY (id)
);
 <br>
INSERT INTO person VALUES (NULL, 'Antonio Paz');
 <br>
SELECT @last := LAST_INSERT_ID();
 <br>
INSERT INTO shirt VALUES
(NULL, 'polo', 'blue', @last),
(NULL, 'dress', 'white', @last),
(NULL, 't-shirt', 'blue', @last);
 <br>
INSERT INTO person VALUES (NULL, 'Lilliana Angelovska');
 <br>
SELECT @last := LAST_INSERT_ID();
 <br>
INSERT INTO shirt VALUES
(NULL, 'dress', 'orange', @last),
(NULL, 'polo', 'red', @last),
(NULL, 'dress', 'blue', @last),
(NULL, 't-shirt', 'white', @last);
 <br>
SELECT * FROM person;
+----+---------------------+
| id | name                |
+----+---------------------+
|  1 | Antonio Paz         |
|  2 | Lilliana Angelovska |
+----+---------------------+
 <br>
r e
SELECT * FROM shirt;
+----+---------+--------+-------+
| id | style   | color  | owner |
+----+---------+--------+-------+
|  1 | polo    | blue   |     1 |
|  2 | dress   | white  |     1 |
|  3 | t-shirt | blue   |     1 |
|  4 | dress   | orange |     2 |
|  5 | polo    | red    |     2 |
|  6 | dress   | blue   |     2 |
|  7 | t-shirt | white  |     2 |
+----+---------+--------+-------+
 <br>
 <br>
SELECT s.* FROM person p, shirt s
 WHERE p.name LIKE 'Lilliana%'
   AND s.owner = p.id
   AND s.color  'white';
 <br>
+----+-------+--------+-------+
| id | style | color  | owner |
+----+-------+--------+-------+
|  4 | dress | orange |     2 |
|  5 | polo  | red    |     2 |
|  6 | dress | blue   |     2 |
+----+-------+--------+-------+



我错了,网断了。只好拷贝书上的代码了。
rrreeerrreee

mysql> show create table shirt\G

****** ********* ************ 1. row ***************************

Table: shirt
Create Table: CREATE TABLE `shirt` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`style` enum('t-shirt','polo','dress') NOT NULL,
`color` enum('red','blue','orange','white','black') NOT NULL,
`owner` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1
1 row in set (0.01 sec)

mysql>

The above is the detailed content of Summarize knowledge related to Mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.