我可以从子查询中获取MAX和COUNT吗?

时间:2014-04-17 19:38:44

标签: mysql sql join subquery

请查看this SQL Fiddle。我有一个author表和一个book表,你知道它是如何工作的:

create table author (
  id int auto_increment,
  first_name varchar(50),
  last_name varchar(50),
  birthdate date,
  death date null,
  birthplace varchar(50),
  number_of_children int,
  mother_name varchar(100),
  other_meaningless_stuff text,
  PRIMARY KEY (id)
);

create table book (
  id int auto_increment,
  author_id int,
  title varchar(100),
  release_date date,
  PRIMARY KEY (id)
);

用简单的英语,我想获得 author 中的所有字段,作者死后发布的书籍数量,以及他去世后发布的最后一本书。在MySQL中,我可以:

select author.*,
  (select count(*) from book where book.author_id=author.id and book.release_date > author.death) post_mortem_books,
  (select max(release_date) from book where book.author_id=author.id and book.release_date > author.death) last_post_mortem_book
from author;

正如您所看到的,两个子查询都具有完全相同的WHERE子句 - 但这似乎是浪费,因为两个表都非常大。另一个解决方案是GROUP BY查询中的每个字段,但这可能是vwey慢。如何以更优化的方式获得结果?

1 个答案:

答案 0 :(得分:1)

不在select子句中使用嵌套子查询。因此,请切换查询以使用joingroup by

select a.*,
       sum(case when b.release_date > a.death then 1 else 0 end) as post_mortem_books,
       max(case when b.release_date > a.death then release_date end) as last_post_mortem_book
from author a left outer join
     books b
     on a.author_id = b.author_id
group by a.author_id