MySQL正确的SELECT方式涉及许多表

时间:2011-07-01 09:25:14

标签: mysql sql select

我有电影数据库,有这些表:new_movies,rating,critic_ratings,colors

我正在尝试执行这个SELECT语句,它将使用'mid'(电影ID)在同一部电影上组合这4个表:

SELECT DISTINCT 
   new_movies.*,
   movies_db.*,
   ratings.rating,
   ratings.count,color,
   critic_ratings.rating AS critic_ratings 
FROM 
   new_movies 
INNER JOIN 
   movies_db 
ON 
   new_movies.mid = movies_db.mid 
LEFT JOIN 
   ratings 
ON 
   new_movies.mid = ratings.mid 
LEFT JOIN 
   colors 
ON 
   new_movies.mid = colors.mid 
LEFT JOIN 
   critic_ratings 
ON 
   new_movies.mid = critic_ratings.mid 
ORDER BY 
   title ASC

但是我收到了这个错误:

  

SELECT会检查更多   MAX_JOIN_SIZE行;检查你的地方   并使用SET SQL_BIG_SELECTS = 1或SET   SQL_MAX_JOIN_SIZE =#,如果是SELECT   好

如何正确执行此查询?

3 个答案:

答案 0 :(得分:1)

如果您不想启用大选择,可以使用相关子查询对其进行改造。 (我不知道你是否仍然会达到极限。)

SELECT DISTINCT 
   new_movies.*,
   movies_db.*,
   (SELECT rating FROM ratings        WHERE new_movies.mid = ratings.mid) AS rating,
   (SELECT count  FROM ratings        WHERE new_movies.mid = ratings.mid) AS rating_count,
   (SELECT color  FROM colors         WHERE new_movies.mid = colors.mid)  AS colour,
   (SELECT rating FROM critic_ratings WHERE new_movies.mid = critic_ratings.mid) AS critic_ratings
FROM 
  new_movies 
INNER JOIN 
  movies_db 
    ON new_movies.mid = movies_db.mid 
ORDER BY 
   title ASC

另外,值得一个测试,看看LEFT JOIN是否真的是原因,你能执行以下操作吗?

SELECT DISTINCT 
   new_movies.*,
   movies_db.*
FROM 
  new_movies 
INNER JOIN 
  movies_db 
    ON new_movies.mid = movies_db.mid 
ORDER BY 
   title ASC

答案 1 :(得分:0)

为什么你有电影和new_movies表?肯定一个发布日期字段就足够了 - 也会切断一个连接......

为此,我将创建该数据的视图并进行查询。

但回到你的问题:

SELECT DISTINCT
    new_movies.*,
    movies_db.*,
    ratings.rating,
    ratings.count,
    color,
    critic_ratings.rating AS critic_ratings
FROM
    new_movies
INNER JOIN
    movies_db
ON
    new_movies.mid = movies_db.mid
LEFT JOIN
    ratings
ON
    new_movies.mid = ratings.mid
LEFT JOIN
    colors
ON
    new_movies.mid = colors.mid
LEFT JOIN
    critic_ratings
ON
    new_movies.mid = critic_ratings.mid
ORDER BY
    title ASC

我看不到任何明显的东西......也许你可以发布解释查询的结果?

答案 2 :(得分:0)

您的查询本身没有问题。只是你选择了所有的电影(没有WHERE,没有LIMIT),并且因为你正在加入评级,例如,它将加入每部电影的所有评级。您只是达到了允许连接的最大数据量。

我不确定你为什么需要选择所有电影。也许你可以使用限制。否则,您只需在错误消息中尝试解决方案。