查询2张表join

Query 2 tables join

我想获取类型等于ID_GENRE = 8的所有电影。这是我正在做的查询:

http://l4c.me/fullsize/2-tablas-1434140362.png

$query_GetSimilar = sprintf("SELECT * FROM z_movie,z_movie_genre ORDER BY z_movie.visits DESC WHERE z_movie_genre.id_genre = 8 LIMIT 18");
$GetSimilar = mysql_query($query_GetSimilar, conect::dbconect()) or die(mysql_error());
$row_GetSimilar = mysql_fetch_assoc($GetSimilar);
$totalRows_GetSimilar = mysql_num_rows($GetSimilar);

但是我跳下错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE z_movie_genre.id_genre = 8 LIMIT 18' at line 1

简单搜索一下,看看能不能把'order by'放在'where'之前。

好的,现在我的查询是:

$query_GetSimilar = sprintf("SELECT * FROM z_movie,z_movie_genre WHERE z_movie_genre.id_genre=8  ORDER BY z_movie.visits DESC LIMIT 18");
$GetSimilar = mysql_query($query_GetSimilar, conect::dbconect()) or die(mysql_error());
$row_GetSimilar = mysql_fetch_assoc($GetSimilar);
$totalRows_GetSimilar = mysql_num_rows($GetSimilar);

但我没有得到预期的结果

注:

  • WHERE 应该在 ORDER BY
  • 之前
  • 您可以使用 INNER JOIN 获得两个连接 table,假设它们具有连接 id/column。

比如z_moviez_movie_genretable都有id_genre列相互连接,你可以试试这个:

$query_GetSimilar = sprintf("SELECT * FROM z_movie
                               INNER JOIN z_movie_genre ON z_movie.id_genre = z_movie_genre.id_genre
                               WHERE z_movie_genre.id_genre = 8
                               ORDER BY z_movie.visits DESC
                               LIMIT 18");