sql - 排序结果与 mysql 中的内连接和左连接不同

标签 sql mysql database sorting join

我刚刚在我所做的查询中发现了这种不规则性,为什么使用内连接和左连接时结果不同?一方面,结果在临时命中表和最终查询中都是有序的?

我举了一个小例子来说明问题:

# cleanup
drop temporary table if exists ids;
drop temporary table if exists arts;

# create temporary tables
create temporary table arts ( id int, title varchar(100), posted datetime );
create temporary table ids ( id int, artid int );

# insert dummy articles
insert into arts ( id, title, posted ) VALUES ( 1, 'a', '2010-04-01' );
insert into arts ( id, title, posted ) VALUES ( 2, 'b', '2010-07-01' );
insert into arts ( id, title, posted ) VALUES ( 3, 'c', '2010-06-01' );
insert into arts ( id, title, posted ) VALUES ( 4, 'd', '2010-08-01' );

# insert ordered list of hits
insert into ids ( id, artid ) values ( 1, 4 );
insert into ids ( id, artid ) values ( 2, 2 );
insert into ids ( id, artid ) values ( 3, 3 );
insert into ids ( id, artid ) values ( 4, 1 );

# execute queries
select i.artid, a.posted from ids i left join arts a on a.id = i.artid;
select i.artid, a.posted from ids i inner join arts a on a.id = i.artid;

# cleanup
drop temporary table if exists arts;
drop temporary table if exists ids;

第一个查询返回:

4,2,3,1 (as expected, ordered by posted-column descending)

第二个返回:

1,2,3,4 (ordered by pk?)

最佳答案

这是您所期望的;在第一个查询中选择的 i.ids 是 1、2、3(大概后来是 4),它们按顺序得到 d、c 和 b。第二张表中选择的i.ids为2,3,4匹配b,c,a。

where 条件从 join 中挑选出三个任意选择的行,并在 order by 之前应用;这大概是导致混淆的原因。

关于sql - 排序结果与 mysql 中的内连接和左连接不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3281006/

相关文章:

sql - 使用连接表选择属于另外两个的行

php - laravel 4.2 中的子查询

mysql - Node mysql插入到多对多表

php - Sulu CMS GET-请求错误

sql组中最低运行余额

mysql - 为什么这个带有 NOT IN 语句的 MySQL 查询这么慢?

MySQL autoincrement 绑定(bind)一个属性

ios - 为什么每次访问我的关系对象时都会重新初始化?

mysql - 我如何知道何时应该优化我的查询?

php - 具有多条记录的 LAST_INSERT_ID() 插入 MySQL