如何优化此查询?

时间:2009-12-21 07:32:33

标签: mysql

从视频中选择sum(viewcount),其中id为(     从syndicatedvideos中选择videoid,其中videoid in(从syndicatedvideos中选择syndicatedvideoid,其中videoid = 31)     联盟     从syndicatedvideos中选择syndicatedvideoid,其中videoid in(选择syndicatedvideoid来自syndicatedvideos,其中videoid = 31))或id(31)。

如何优化上述查询?

4 个答案:

答案 0 :(得分:0)

我认为这应该有用。

select sum(viewcount)  from video 
where id in( select syndicatedvideoid from syndicatedvideos where videoid=31) or or id in (31)

请检查并验证。感谢。

答案 1 :(得分:0)

SELECT sum(video.viewcount) FROM video 
  LEFT JOIN syndicatedvideos sv1 ON video.id=sv1.videoid  
  LEFT JOIN syndicatedvideos sv2 ON video.id=sv1.syndicatedvideoid 
WHERE 
  sv1.videoid=31 OR
  sv2.videoid=31 OR
  video.id=31;

答案 2 :(得分:0)

select sum(viewcount)
from video
where id in(

    select id from(
        select videoid as id
        from syndicatedvideos

        union

        select syndicatedvideoid as id
        from syndicatedvideos)

    where id in(
        select syndicatedvideoid
        from syndicatedvideos
        where videoid=31)

) or id in (31)

答案 3 :(得分:0)

select sum(viewcount)  
from video v
where exists (
    select 1 
    from syndicatedvideos sv 
    where (
        v.id = sv.videoid
        or v.id = sv.syndicatevideoid )
    and exists (
        select 1 
        from syndicatedvideos sv2
        where sv.videoid = sv2.syndicatevideoid
        and sv2.videoid=31)
) 
or id = 31.

我改变了什么:

  • 用=
  • 替换最后一个in()
  • 将主要的in()子查询替换为匹配两者的exists videoid和syndicatevideoid,因此避免与第二个子条款结合
  • 很好地格式化以帮助理解: - )