2016-06-07 32 views
0

我需要从书架中获取id(或*,whatever),其中包含出版商为我正在处理的此项目发布的大部分书籍,但我无法让我的头在获得正确的查询。我使用普通的SQL。从另一个实体中选择具有最大属性的行

下面是我的数据库如何设置,简化的图。 Diagram of the database 编辑:entity_3应该是出版商,我的坏。

回答

0

这应该这样做,但由于您可能会获得多个货架,每个货架具有相同的最大数量,因此它可能会返回多个货架ID。如果这不是你想要的,你可以用几种方法将它剪成一个ID,例如,通过在shelf_id上执行MIN()。

select b.id_shelf 
    from (select s.id_shelf,   
       count(*) as sp_count  
      from shelf s,  
       book b   
     where s.id_shelf = b.id_shelf 
      and b.publisher = @publisher 
     group by s.id_shelf 
     ) b 
where b.sp_count = (select max(a.sp_count) 
         from (select s.id_shelf,  
            count(*) as sp_count  
           from shelf s,   
            book b   
           where s.id_shelf = b.id_shelf 
           and b.publisher = @publisher 
           group by s.id_shelf 
          ) a 
        ) b 
相关问题