douyi9705 2010-10-04 16:17
浏览 34
已采纳

这个MySQL查询是JOIN,常规查询还是两者兼而有之?

I need to get data from 3 different tables. I know the basics about JOINs but when it comes to more complicated queries like getting data from 3 or more tables using JOIN I get a little confused and I just start playing with the queries writing what make sense to me, like the next one:

SELECT movies.imdbID,
  movies.title,
  movies.year,
  movie_ratings.votes,
  movie_ratings.total_value,
  movie_ratings_external.votes,
  movie_ratings_external.total_value
FROM movies, movie_ratings_external
LEFT JOIN movie_ratings ON movie_ratings.imdbID = movie_ratings_external.imdbID
WHERE movies.imdbID = movie_ratings_external.imdbID
ORDER BY movie_ratings.votes DESC, movie_ratings_external.votes DESC
LIMIT 30

This query works. I get the selected fields from the correct tables and ordered the right way, but I think I'm mixing up things (like regular querying two tables and JOINing between two tables) and I'm sure theres a better/more efficient way to accomplish the same purpouse.

Any DB geek available?

  • 写回答

4条回答 默认 最新

  • dongli564510 2010-10-04 16:29
    关注

    Modified your query just a tad bit. Everything else was pretty much spot on.

    I am not exactly sure what you call a "regular query" but Joins are pretty much the very basic part of a regular query.

    In your old query, this part FROM movies, movie_ratings_external was basically a CROSS JOIN. Replaced it with a JOIN (i used a LEFT JOIN assuming that you always wanted to return all the movies but basic intention was that the CROSS JOIN with the filtering in the WHERE is a LOT more inefficient because you are manipulating more ROWS - especially unnecessary ones)

    Think of it this way. Every Join statement in your SELECT returns a set of row which are then JOINED with the next table in the JOIN. The idea should be to try an filter rows progressively with each join as far as possible so that you arent getting unnecessary tuples. Thats where the ON statements come in.

    Removed

    SELECT 
      movies.imdbID,
      movies.title,
      movies.year,
      movie_ratings.votes,
      movie_ratings.total_value,
      movie_ratings_external.votes,
      movie_ratings_external.total_value
    FROM movies 
    LEFT OUTER JOIN movie_ratings_external
         ON movies.imdbID = movie_ratings_external.imdbID
    LEFT JOIN movie_ratings 
         ON movie_ratings.imdbID = movie_ratings_external.imdbID
    ORDER BY movie_ratings.votes DESC, movie_ratings_external.votes DESC
    LIMIT 30
    

    Hope that helps!!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)