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

你可能感兴趣的:(sql)