带有分组依据的子查询ORDER BY子句?

时间:2020-04-29 00:48:09

标签: mysql group-by sql-order-by

我正在尝试从子实体中获取最后x条记录(以最新的顺序为最后一个),例如del = 0,但是由于变通方法,查询速度很慢,或者忽略了排序。

样本数据:

create table child (
id int unsigned not null auto_increment primary key,
name varchar(20) not null default '',
parent_id int unsigned not null,
category_id tinyint unsigned not null,
del tinyint(1) unsigned not null default 0,
index idx_parent(parent_id)
);

create table parent (
id int unsigned not null auto_increment primary key,
name varchar(20) not null default ''
);

create table category (
id tinyint unsigned not null auto_increment primary key,
name varchar(20) not null default ''
);

insert into category (name) values ('A'), ('B'), ('C');
insert into parent (name) values ('Father'), ('Mother'), ('Grand-Father'), ('Grand-Mother');
insert into child(name, parent_id, category_id) values
('Kid', 1, 2), ('Infant', 3, 1), ('Teen', 2, 3), ('Boy', 1, 1),('Girl', 3, 2);

查询:

select * from (
    select * from child
    # workaround 1 (slowing down the query)
    # group by id
    order by id desc
) ch
inner join parent p on p.id = ch.parent_id
inner join category c on c.id = ch.category_id
where ch.del = 0
# workaround 2 (slowing down the query)
# order by ch.id desc
limit 10

请参见db-fiddle链接。

在子查询中不使用del = 0,因为它没有索引,最好先用主索引进行排序,然后再进行过滤,因为99.9%的del = 0的计算结果为true。

0 个答案:

没有答案