distinct 和 order by

问题描述:
有两个sql,我以为查询结果会一样,但是结果却是天差地别:
第一条语句:
select  distinct(ic.companyId) as companyId  from industry_company ic join funding f on f.companyId=ic.companyId join company c on c.id = ic.companyId where  (c.active = 'Y' or c.active is null) and (ic.active='Y' or ic.active is null)   and (f.active is null or f.active='Y') and ic.industryId = 387 order by f.publishDate desc,  f.fundingDate desc  limit 5;
查询结果:
companyId |
+-----------+
|    352295 |
|    348968 |
|    270596 |
|    328046 |
|    246927 |
+---------

第二条语句:
select  distinct(ic.companyId) as companyId, f.publishDate as date  from industry_company ic join funding f on f.companyId=ic.companyId join company c on c.id = ic.companyId where  (c.active = 'Y' or c.active is null) and (ic.active='Y' or ic.active is null)   and (f.active is null or f.active='Y') and ic.industryId = 387 order by f.publishDate desc,  f.fundingDate desc  limit 5;
执行结果变了:
 companyId | date                |
+-----------+---------------------+
|    143467 | 2018-04-20 11:18:18 |
|    234394 | 2018-04-04 15:04:00 |
|    352295 | 2018-02-24 08:00:00 |
|    348968 | 2018-02-09 08:50:33 |
|    347770 | 2018-02-05 11:14:00 |


可以看到 companyId 列表 差异很大 , 解释起来原因如下:
1、 distinct 会作用其后所有列
2、distinct 里如果缺乏ordey by 的字端,那么order by 没有作用

先distinct 后order by ,如果distinct 缺乏 order by 里面的字段,那么 该如何排序呢! 



下面是SELECT语句的逻辑执行顺序:
1、FROM
2、ON
3、JOIN
4、WHERE
5、GROUP BY
6、WITH CUBE or WITH ROLLUP
7、HAVING
8、SELECT
9、DISTINCT
10、ORDER BY
11、TOP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值