MySQL中distinct语句去查询重复记录及相关的性能讨论
在 MySQL 查询中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。 关键词 DISTINCT 用于返回唯一不同的值,就是去重啦。用法也很简单: SELECT DISTINCT * FROM tableName DISTINCT 这个关键字来过滤掉多余的重复记录只保留一条。 另外,如果要对某个字段去重,可以试下: SELECT *,COUNT(DISTINCT nowamagic) FROM table GROUP BY nowamagic 这个用法,MySQL的版本不能太低。 在编写查询之前,我们甚至应该对过滤条件进行排序,真正高效的条件(可能有多个,涉到同的表)是查询的主要驱动力,低效条件只起辅助作用。那么定义高效过滤条件的准则是什呢?首先,要看过滤条件能否尽快减少必须处理的数据量。所以,我们必须倍加关注条件的写方式。 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 ,因为考虑到某个客户可以是大买家,最近订购了好几台蝙蝠车。 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表的筛选条件将失效,因为是左外连接,左表的所有列都将出现在这次连接结果集中)。 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 custname from customers where city = 'GOTHAM' and custid in (select o.custid from orders o,articles a where a.artname = 'BATMOBILE' and a.artid = od.artid and od.ordid = o.ordid and o.ordered >= somefunc) 在这个例子中,内层查询不再依赖外层查询,它已变成了非关联子查询( uncorrelated subquery ),只须执行一次。很显然,这段代码采用了原有的执行流程。在本节的前一个例子 中 ,必须先搜寻符合地点条件的客户(如均来自 GOTHAM ),接着依次检查各个订单。而现在,订购了蝙蝠车的客户,可以通过内层查询获得。 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 字段有索引,这个方法会更快,否则,这个聪明巧妙的举措就会黯然失色。 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 语句的第一步。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |