mysql select 语句实例详解
简单查询
<code class="language-sql">SELECT columna columnb FROM mytable;</code>
ORDER BY查询
<code class="language-sql">SELECT college, region, seed FROM tournament ORDER BY region, seed; SELECT college, region AS r, seed AS s FROM tournament ORDER BY r, s; SELECT college, region, seed FROM tournament ORDER BY 2, 3; </code>
--要以相反的顺序进行分类,应把DESC(降序)关键字添加到ORDER BY子句中的列名称中。默认值为升序;该值可以使用ASC关键词明确地指定。
<code class="language-sql">SELECT a, COUNT(b) FROM test_table ORDER BY a DESC;</code>
GROUP BY having查询
<code class="language-sql">SELECT a, COUNT(b) FROM test_table GROUP BY a DESC; SELECT COUNT(col1) AS col2 FROM t GROUP BY col2 HAVING col2 = 2;</code>
HAVING不能用于应被用于WHERE子句的条目,不能编写如下语句:
<code class="language-sql">SELECT col_name FROM tbl_name HAVING col_name > 0;</code>
而应该这么编写
<code class="language-sql">SELECT col_name FROM tbl_name WHERE col_name > 0;</code>
HAVING子句可以引用总计函数,而WHERE子句不能引用:
<code class="language-sql">SELECT user, MAX(salary) FROM users GROUP BY user HAVING MAX(salary)>10;</code>
LIMIT查询
<code class="language-sql">SELECT * FROM tbl LIMIT 10; # Retrieve rows 0-9; SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15;</code>
如果要恢复从某个偏移量到结果集合的末端之间的所有的行,您可以对第二个参数是使用比较大的数。 --以下语句可以恢复从第96行到最后的所有行:
<code class="language-sql">SELECT * FROM tbl LIMIT 95,18446744073709551615;</code>
SELECT...INTO OUTFILE
SELECT...INTO OUTFILE 'file_name'形式的SELECT可以把被选择的行写入一个文件中。该文件被创建到服务器主机上,因此您必须拥有FILE权限,才能使用此语法。file_name不能是一个原有的文件。
SELECT...INTO OUTFILE语句的主要作用是让您可以非常快速地把一个表转储到服务器机器上。如果您想要在服务器主机之外的部分客户主机上创建结果文件,您不能使用SELECT...INTO OUTFILE。在这种情况下,您应该在客户主机上使用比如“mysql –e "SELECT ..." > file_name”的命令,来生成文件。
SELECT...INTO OUTFILE是LOAD DATA INFILE的补语;用于语句的exort_options部分的语法包括部分FIELDS和LINES子句,这些子句与LOAD DATA INFILE语句同时使用。
在下面的例子中,生成一个文件,各值用逗号隔开。这种格式可以被许多程序使用
<code class="language-sql">SELECT a,b,a+b INTO OUTFILE '/tmp/result.text' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM test_table;</code>
如果您使用INTO DUMPFILE代替INTO OUTFILE,则MySQL只把一行写入到文件中,不对任何列或行进行终止,也不执行任何转义处理。如果您想要把一个BLOB值存储到文件中,则这个语句是有用的。
UNION
UNION用于把来自许多SELECT语句的结果组合到一个结果集合中,语法如下:
<code class="language-sql">SELECT ... UNION [ALL | DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...]</code>
列于每个SELECT语句的对应位置的被选择的列应具有相同的类型。(例如,被第一个语句选择的第一列应和被其它语句选择的第一列具有相同的类型。)在第一个SELECT语句中被使用的列名称也被用于结果的列名称。
如果您对UNION不使用关键词ALL,则所有返回的行都是唯一的,如同您已经对整个结果集合使用了DISTINCT。如果您指定了ALL,您会从所有用过的SELECT语句中得到所有匹配的行。
您可以在同一查询中混合UNION ALL和UNION DISTINCT。被混合的UNION类型按照这样的方式对待,即DISTICT共用体覆盖位于其左边的所有ALL共用体。DISTINCT共用体可以使用UNION DISTINCT明确地生成,或使用UNION(后面不加DISTINCT或ALL关键词)隐含地生成。
简单例子
<code class="language-sql">(SELECT a FROM tbl_name WHERE a=10 AND B=1) UNION (SELECT a FROM tbl_name WHERE a=11 AND B=2) ORDER BY a LIMIT 10;</code>
ALL, DISTINCT和DISTINCTROW
ALL, DISTINCT和DISTINCTROW选项指定是否重复行应被返回。如果这些选项没有被给定,则默认值为ALL(所有的匹配行被返回)。DISTINCT和DISTINCTROW是同义词,用于指定结果集合中的重复行应被删除。
<code class="language-sql">SELECT DISTINCT a FROM table_name; SELECT COUNT(DISTINCT a) FROM table_name;</code>

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



There are many reasons why MySQL startup fails, and it can be diagnosed by checking the error log. Common causes include port conflicts (check port occupancy and modify configuration), permission issues (check service running user permissions), configuration file errors (check parameter settings), data directory corruption (restore data or rebuild table space), InnoDB table space issues (check ibdata1 files), plug-in loading failure (check error log). When solving problems, you should analyze them based on the error log, find the root cause of the problem, and develop the habit of backing up data regularly to prevent and solve problems.

MySQL uses shared locks and exclusive locks to manage concurrency, providing three lock types: table locks, row locks and page locks. Row locks can improve concurrency, and use the FOR UPDATE statement to add exclusive locks to rows. Pessimistic locks assume conflicts, and optimistic locks judge the data through the version number. Common lock table problems manifest as slow querying, use the SHOW PROCESSLIST command to view the queries held by the lock. Optimization measures include selecting appropriate indexes, reducing transaction scope, batch operations, and optimizing SQL statements.

In MySQL database operations, string processing is an inevitable link. The SUBSTRING_INDEX function is designed for this, which can efficiently extract substrings based on separators. SUBSTRING_INDEX function application example The following example shows the flexibility and practicality of the SUBSTRING_INDEX function: Extract specific parts from the URL For example, extract domain name: SELECTSUBSTRING_INDEX('www.mysql.com','.',2); Extract file extension to easily get file extension: SELECTSUBSTRING_INDEX('file.pdf','.',-1); Processing does not exist

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

The MySQL primary key cannot be empty because the primary key is a key attribute that uniquely identifies each row in the database. If the primary key can be empty, the record cannot be uniquely identifies, which will lead to data confusion. When using self-incremental integer columns or UUIDs as primary keys, you should consider factors such as efficiency and space occupancy and choose an appropriate solution.

For production environments, a server is usually required to run MySQL, for reasons including performance, reliability, security, and scalability. Servers usually have more powerful hardware, redundant configurations and stricter security measures. For small, low-load applications, MySQL can be run on local machines, but resource consumption, security risks and maintenance costs need to be carefully considered. For greater reliability and security, MySQL should be deployed on cloud or other servers. Choosing the appropriate server configuration requires evaluation based on application load and data volume.

MySQL can return JSON data. The JSON_EXTRACT function extracts field values. For complex queries, you can consider using the WHERE clause to filter JSON data, but pay attention to its performance impact. MySQL's support for JSON is constantly increasing, and it is recommended to pay attention to the latest version and features.
