search
HomeDatabaseMysql Tutorial利用MySQL的left join找最大值所在的列

嗯,写文章之前,还是照例来一小段评论吧。 最近比较火的一条新闻是Mongodb获得了上千万的融资,估值达到十亿美元了。而开源公司里,Redhat达到这个市值花了将近20年的时间。 对于这条消息,该怎么说呢。首先吧,一个是钱的面值变大了。再怎么说,现在的100

嗯,写文章之前,还是照例来一小段评论吧。

最近比较火的一条新闻是Mongodb获得了上千万的融资,估值达到十亿美元了。而开源公司里,Redhat达到这个市值花了将近20年的时间。

对于这条消息,该怎么说呢。首先吧,一个是钱的面值变大了。再怎么说,现在的100美元也没有九十年代的100美元值钱。另外呢,大数据这个概念炒得真是火呀,现在说起大数据,没有Hadoop,Mongodb,好像就不是在搞大数据了。所以,这里的泡沫真是大呀。

我好像是2010年的时候,才第一次从《程序员》杂志上看到NoSQL这东西的,年少无知的我,看了上面的介绍,也觉得NoSQL要拯救世界了。但越到后面,我接触的越多,就发现,NoSQL也就那样。很多工作在互联网公司的程序员会说NoSQL要统治世界了,但实际上,这东西,至少目前来说,真的没有关系数据库重要。也因此,我基本上没有花时间去了解这些东西,当然,我数据库方面的学习本来就非常欠缺,罪过罪过,这一年里要尽量补过。

好了,来说说今天为什么要写这篇文章。

今天我在看MySQL那厚厚的四千多页的文档,看到198页的一个例子,例子里用三种方法获得数据表里面的最大值,有一个是使用 left join实现的,让我非常看不懂,因此就搜索了下,看了几个人写的博客,搞明白了个大概。

首先,你先创建一个数据库,或者使用当前已有的数据库,创建如下表:

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));

然后插入一些示例数据,如下:

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);

执行:

select * from shop;

可以看到如下的结果:

35

此时,如果我们想获得price最高的那一列数据,记住,不是price最高是多少,而是price最高所在的那列的数据,要怎么写sql呢?其中一种简单的方法如下:

select * from shop where price=(select max(price) from shop);

获得的结果如下:

36

还有另一种更加简单的方法就是使用limit关键字。如下:

select * from shop order by price desc limit 1;

上述两种方法,稍微学习过SQL的人,都很容易明白意思,然而下面这种方式,就比较困难了:

select s1.* from shop s1 left join shop s2 on s1.price 
<p>同样可以得到上图中的结果,这到底是为什么呢? 这两篇博客可以让我们多少了解清楚上述SQL到底做了什么:MYSQl left join 联合查询效率分析 ,以及 关于 MySQL LEFT JOIN 你可能需要了解的三点 。</p>
<p>下面我来自己解释一下:</p>
<p>首先,on 条件语句,是对右表的过滤,上述语句中就是对s2的过滤。left join的执行过程是这样的,首先,从左表中拿出一条数据,然后根据on条件语句,到右边中取出符合条件的数据,把两个拼接起来,组成一个在内存里的新表。注意,这里有个过程,比如咱们这里是左表右表都是同一个表,从左表取出一条数据之后,其实是会从右表中取出所有的符合条件的数据,拼接。然后再从左表取下一条数据,再次从右表中取出所有符合条件的数据,拼接,递归下去,形成一个新表。然后,where语句再对这个新表进行一次过滤,过滤完毕就是展现在我们眼前的样子了。</p>
<p>所以,上述语句,就是先从原表里取出一条数据A,然后再回原表,取满足B.price > A.price的数据,然后继续,左表继续取下一条,然后再回原表,取满足B.price > A.price的数据 。最后,这个过程的结果拼接为一个新表,再用where语句进行过滤。</p>
<p>也许说完这些,你还看不怎么懂,没关系,我稍微修改下上述的SQL语句:</p>
<pre class="brush:php;toolbar:false">select * from shop s1 left join shop s2 on s1.price 
<p>生成的结果如下:</p>
<p><img src="/static/imghwm/default1.png" data-src="http://www.68idc.cn/help/uploads/allimg/150119/0Q5445504-2.png" class="lazy" alt="37" border="0"    style="max-width:90%" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" title="37"  style="max-width:90%"></p>
<p>之前那条语句,并没有把所有查询到的字段都展示出来,这次把所有字段都展示出来,并把where语句去掉,展示出结果之后 ,对之前那条语句是不是一下子就明白了呢?</p>
<p>说实在的,这句</p>
<pre class="brush:php;toolbar:false">select s1.* from shop s1 left join shop s2 on s1.price 
<p>真的是很好的利用了left join的特性的。price值最大的那个数据,一定不满足 s1.price<s2.price join>

    <p class="copyright">
        原文地址:利用MySQL的left join找最大值所在的列, 感谢原作者分享。
    </p>
    
    
</s2.price></p>

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 InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor