使用连接将带有子选择的MySQL查询转换为单个查询

时间:2017-07-02 18:18:09

标签: mysql

如何将此查询转换为使用连接的查询:

SELECT pm.name,(SELECT chapter FROM puzz_chapter WHERE (grup = 1 OR grup2 = 1) AND manga = pm.mangaId ORDER BY chapterId DESC LIMIT 1) as sonbolum FROM puzz_manga as pm;

1 个答案:

答案 0 :(得分:1)

要使用连接,您可以在left join子句中移动子查询,如下所示:

select    pm.name,
          pc.chapter as sonbolum  
from      puzz_manga pm
left join (select  manga, chapter 
          from     puzz_chapter 
          where    (grup = 1 or grup2 = 1) 
          order by chapterId desc
          limit    1) pc
       on pc.manga = pm.mangaId;

但也许您正在寻找避免子查询的方法。在这种情况下,在MySql中没有有效的方法(在撰写本文时)。一种方法是使用group_concat,然后从中提取第一个值,但我希望它的效率低于您已有的解决方案:

select    pm.name,
          substring_index(group_concat(pc.chapter order by pc.chapterId desc), ",", 1) 
                 as sonbolum
from      puzz_manga pm
left join puzz_chapter pc
       on (pc.grup = 1 or pc.grup2 = 1) 
      and pc.manga = pm.mangaId
group by  pm.mangaId;

查看在rextester.com

上运行的两个查询