简体   繁体   English

如何使用PHP在MySQL中过滤数据(一对多关系)

[英]How to filter data in MySQL (One to many relationship) using PHP

What I Want To Do 我想做的事

The user will send a value using GET and I will store the value in a variable named $category1 . 用户将使用GET发送一个值,并将该值存储在名为$category1的变量$category1 Now all the rows which contain the value of $category1 will display. 现在将显示所有包含$category1值的行。 This is like a search system. 这就像一个搜索系统。

This is my code 这是我的代码

$stmt = $conn->prepare("SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT genres.genres_name SEPARATOR ', ') AS genres

FROM tmdb_movies

JOIN genres ON genres.genres_tmdb_id=tmdb_movies.tmdb_id

WHERE EXISTS (SELECT genres.genres_name FROM genres WHERE genres.genres_name = '$category1');

GROUP BY tmdb_movies.movie_title");

Error: Because of WHERE Exist line (IDK, if I should use it or no) 错误:由于WHERE Exist行(IDK,如果我应该使用它还是不使用它)

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'DataBaseName.tmdb_movies.movie_title'; 致命错误:未捕获的PDOException:SQLSTATE [42000]:语法错误或访问冲突:1140在没有GROUP BY的聚合查询中,SELECT列表的表达式#1包含非聚合列'DataBaseName.tmdb_movies.movi​​e_title'; this is incompatible with sql_mode=only_full_group_by 这与sql_mode = only_full_group_by不兼容

Let me explain my Table Structure now 现在让我解释一下我的表结构

I have two tables 我有两张桌子

  1. tmdb_movies (it store movie title and tmdb_id) tmdb_movies (它存储电影标题和tmdb_id)
  2. genres (It stores genres, which is connected via tmdb_id) genres (存储流派,通过tmdb_id连接)

The example of tables. 表的示例。

tmdb_movies table tmdb_movies

tmdb_id     movie_title
1           The_Dark_Night
2           Logan
3           IronMan

genres table genres

tmdb_id       genres
 1            Action
 1            Crime
 1            Drama
 2            Action
 2            Drama
 3            Action
 3            Comedy

In 5.7 the sqlmode is set by default to: 在5.7中,sqlmode默认设置为:

ONLY_FULL_GROUP_BY,
 NO_AUTO_CREATE_USER,
 STRICT_TRANS_TABLES,
 NO_ENGINE_SUBSTITUTION

To remove the clause ONLY_FULL_GROUP_BY you can do this: 要删除子句ONLY_FULL_GROUP_BY,您可以这样做:

SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

This supposed you need to make that GROUP BY with non aggregated columns. 假设您需要使用非聚合列来创建该GROUP BY。

otherwise i tested your code locally it working perfectly fine. 否则,我会在本地测试您的代码,效果非常好。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM