设计高效的SQL语句过滤条件
在编写查询之前,我们甚至应该对过滤条件进行排序,真正高效的条件(可能有多个,涉到同的表)是查询的主要驱动力,低效条件只起辅助作用。那么定义高效过滤条件的准则是什呢?首先,要看过滤条件能否尽快减少必须处理的数据量。所以,我们必须倍加关注条件
在编写查询之前,我们甚至应该对过滤条件进行排序,真正高效的条件(可能有多个,涉到同的表)是查询的主要驱动力,低效条件只起辅助作用。那么定义高效过滤条件的准则是什呢?首先,要看过滤条件能否尽快减少必须处理的数据量。所以,我们必须倍加关注条件的写方式。
假设有四个表: customers 、 orders 、 orderdetail 、 articles ,现在假设 SQL 要处理的问题是:找出最近六个月内居住在 Gotham 市、订购了蝙蝠车的所有客户。当然,编写这个查询有多种方法, ANSI SQL 的推崇者可能写出下列语句:
select distinct c.custname from customers c join orders o on o.custid = c.custid join orderdetail od on od.ordid = o.ordid join articles a on a.artid = od.artid where c.city = 'GOTHAM' and a.artname = 'BATMOBILE' and o.ordered >= somefunc
其中, somefunc 是个函数,返回距今六个月前的具体日期。注意上面用了 distinct ,因为考虑到某个客户可以是大买家,最近订购了好几台蝙蝠车。
暂不考虑优化器将如何改写此查询,我们先看一下这段代码的含义。首先,来自 customers 表的数据应只保留城市名为 Gotham 的记录。接着,搜索 orders 表,这意味着 custid 字段最好有索引,否则只有通过排序、合并或扫描 orders 表建立一个哈希表才能保证查询速度。对 orders 表 ,还要针对订单日期进行过滤:如果优化器比较聪明,它会在连接( join )前先过滤掉一些数据,从而减少后面要处理的数据量;不太聪明的优化器则可能会先做连接,再作过滤,这时在连接中指定过滤条件利于提高性能,例如:
join orders o on o.custid = c.custid and a.ordered >= somefunc
注意,如果是:
left outer join orders o on o.custid = c.custid and a.ordered >= somefunc
此处关于left表的筛选条件将失效,因为是左外连接,左表的所有列都将出现在这次连接结果集中)。
即使过滤条件与连接( join )无关,优化器也会受到过滤条件的影响。例如,若 orderdetail 的主键为( ordid, artid ),即 ordid 为索引的第一个属性,那么我们可以利用索引找到与订单相关的记录。但如果主键是( artid, ordid )就太不幸了(注意,就关系理论而言 ,无论哪个版本都是完全一样),此时的访问效率比( ordid, artid )作为索引时要差,甚至一些数据库产品无法使用该索引(注 3 ),唯一的希望就是在ordid 上加独立索引了。
连接了表 orderdetail 和 orders 之后,来看 articles 表,这不会有问题,因为表 order 包括 artid 字段。最后,检查 articles 中的值是否为 Batmobile 。查询就这样结束了,因为用了 distinct ,通过层层筛选的客户名还必须要排序,以剔除重复项目。
避免在最高层使用 distinct 应该是一条基本规则 。原因在于,即使我们遗漏了连接的某个条件, distinct 也会使查询 " 看似正确 " 地执行 —— 无可否认,发现重复数据容易,发现数据不准确很难,所以避免在最高层使用 distinct 应该是一条基本规则。
发现结果不正确更难,例如,如果恰巧有多位客户都叫 " Wayne " , distinct 不但会剔除由同个客户的多张订单产生的重复项目,也会剔除由名字相同的不同客户产生的重复项目。事实上,应该同时返回具唯一性的客户 ID 和客户名,以保证得到蝙蝠车买家的完整清单。
要摆脱 distinct ,可考虑以下思路:客户在 Gohtam 市,而且满足存在性测试,即在最近六个月订购过蝙蝠车。注意,多数(但非全部) SQL 方言支持以下语法:
select c.custname from customers c where c.city = 'GOTHAM' and exists (select null from orders o, orderdetail od, articles a where a.artname = 'BATMOBILE' and a.artid = od.artid and od.ordid = o.ordid and o.custid = c.custid and o.ordered >= somefunc )
上例的存在性测试,同一个名字可能出现多次,但每个客户只出现一次,不管他有多少订单。有人认为我对 ANSI SQL 语法的挑剔有点苛刻(指 " 蝙蝠车买主 " 的例子),因为上面代码中customers 表的地位并没有降低。其实,关键区别在于,新查询中 customers 表是查询结果的唯一来源(嵌套的子查询会负责找出客户子集),而先前的查询却用了 join 。
这个嵌套的子查询与外层的 select 关系十分密切。如代码第 11 行所示(粗体部分),子查询参照了外层查询的当前记录,因此,内层子查询就是所谓的关联子查询( correlated subquery )。
此类子查询有个弱点,它无法在确定当前客户之前执行。如果优化器不改写此查询,就必须先找出每个客户,然后逐一检查是否满足存在性测试,当来自 Gotham 市的客户非常少时执行效率倒是很高,否则情况会很糟(此时,优秀的优化器应尝试其他执行查询的方式)。
select custname from customers where city = 'GOTHAM' and custid in (select o.custid from orders o, orderdetail od, articles a where a.artname = 'BATMOBILE' and a.artid = od.artid and od.ordid = o.ordid and o.ordered >= somefunc)
在这个例子中,内层查询不再依赖外层查询,它已变成了非关联子查询( uncorrelated subquery ),只须执行一次。很显然,这段代码采用了原有的执行流程。在本节的前一个例子 中 ,必须先搜寻符合地点条件的客户(如均来自 GOTHAM ),接着依次检查各个订单。而现在,订购了蝙蝠车的客户,可以通过内层查询获得。
不过,如果更仔细地分析一下,前后两个版本的代码还有些更微妙的差异。含关联子查询的代码中,至关重要的是 orders 表中的 custid 字段要有索引,而这对另一段代码并不重要,因为这时要用到的索引(如果有的话)是表 customers 的主键索引。
你或许注意到,新版的查询中执行了隐式的 distinct 。的确,由于连接操作,子查询可能会返回有关一个客户的多条记录。但重复项目不会有影响,因为 in 条件只检查该项目是否出现在子查询返回的列表中,且 in 不在乎某值在列表中出现了一次还是一百次。但为了一致性,作为整体,应该对子查询和主查询应用相同的规则,也就是在子查询中也加入存在性测试:
select custname from customers where city = 'GOTHAM' and custid in (select o.custid from orders o where o.ordered >= somefunc and exists (select null from orderdetail od, articles a where a.artname = 'BATMOBILE' and a.artid = od.artid and od.ordid = o.ordid))
或者
select custname from customers where city = 'GOTHAM' and custid in (select custid from orders where ordered >= somefunc and ordid in (select od.ordid from orderdetail od, articles a where a.artname = 'BATMOBILE' and a.artid = od.artid)
尽管嵌套变得更深、也更难懂了,但子查询内应选择 exists 还是 in 的选择规则相同:此选择取决于日期与商品条件的有效性。除非过去六个月的生意非常清淡,否则商品名称应为最有效的过滤条件,因此子查询中用 in 比 exists 好,这是因为,先找出所有蝙蝠车的订单、再检查销售是否发生在最近六个月,比反过来操作要快。如果表 orderdetail 的 artid 字段有索引,这个方法会更快,否则,这个聪明巧妙的举措就会黯然失色。
每当对大量记录做存在性检查时,选择 in 还是 exists 须斟酌。
利于多数 SQL 方言,非关联子查询可以被改写成 from 子句中的内嵌视图。然而,一定要记住的是, in 会隐式地剔除重复项目,当子查询改写为 from 子句中的内嵌视图时,必须要显式地消除重复项目。例如:
select custname from customers where city = 'GOTHAM' and custid in (select o.custid from orders o, (select distinct od.ordid from orderdetail od, articles a where a.artname = 'BATMOBILE' and a.artid = od.artid) x where o.ordered >= somefunc and x.ordid = o.ordid)
总结:保证 SQL 语句返回正确结果,只是建立最佳 SQL 语句的第一步。

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

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

How to check my academic qualifications on Xuexin.com? You can check your academic qualifications on Xuexin.com, but many users don’t know how to check their academic qualifications on Xuexin.com. Next, the editor brings you a graphic tutorial on how to check your academic qualifications on Xuexin.com. Interested users come and take a look! Xuexin.com usage tutorial: How to check your academic qualifications on Xuexin.com 1. Xuexin.com entrance: https://www.chsi.com.cn/ 2. Website query: Step 1: Click on the Xuexin.com address above to enter the homepage Click [Education Query]; Step 2: On the latest webpage, click [Query] as shown by the arrow in the figure below; Step 3: Then click [Login Academic Credit File] on the new page; Step 4: On the login page Enter the information and click [Login];

Download the latest version of 12306 ticket booking app. It is a travel ticket purchasing software that everyone is very satisfied with. It is very convenient to go wherever you want. There are many ticket sources provided in the software. You only need to pass real-name authentication to purchase tickets online. All users You can easily buy travel tickets and air tickets and enjoy different discounts. You can also start booking reservations in advance to grab tickets. You can book hotels or special car transfers. With it, you can go where you want to go and buy tickets with one click. Traveling is simpler and more convenient, making everyone's travel experience more comfortable. Now the editor details it online Provides 12306 users with a way to view historical ticket purchase records. 1. Open Railway 12306, click My in the lower right corner, and click My Order 2. Click Paid on the order page. 3. On the paid page

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

According to news on April 3, Taipower’s upcoming M50 Mini tablet computer is a device with rich functions and powerful performance. This new 8-inch small tablet is equipped with an 8.7-inch IPS screen, providing users with an excellent visual experience. Its metal body design is not only beautiful but also enhances the durability of the device. In terms of performance, the M50Mini is equipped with the Unisoc T606 eight-core processor, which has two A75 cores and six A55 cores, ensuring a smooth and efficient running experience. At the same time, the tablet is also equipped with a 6GB+128GB storage solution and supports 8GB memory expansion, which meets users’ needs for storage and multi-tasking. In terms of battery life, M50Mini is equipped with a 5000mAh battery and supports Ty

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

C drive space is running out! 5 efficient cleaning methods revealed! In the process of using computers, many users will encounter a situation where the C drive space is running out. Especially after storing or installing a large number of files, the available space of the C drive will decrease rapidly, which will affect the performance and running speed of the computer. At this time, it is very necessary to clean up the C drive. So, how to clean up C drive efficiently? Next, this article will reveal 5 efficient cleaning methods to help you easily solve the problem of C drive space shortage. 1. Clean up temporary files. Temporary files are temporary files generated when the computer is running.
