目前,我已设法加入两个表来检索所需的信息。 我现在决定尝试从另一个表(users.user_id)中检索另一条信息,但我正在尝试使用的查询似乎不起作用。如果有人可以帮助查询会很棒。
这是我当前的查询工作正常。
"SELECT films.movie_title, films.rating, films.actor, reviewed.review
FROM films
INNER JOIN reviewed
ON films.movie_id=reviewed.movie_id";
以下是用于从三个表中获取数据但不能正常工作的查询
"SELECT films.movie_title, films.rating, films.actor, reviewed.review users.name
FROM films
OUTER JOIN reviewed, users
ON films.movie_id=reviewed.movie_id && films.user_id=users.user_id";
数据库:film
表films
的表结构
CREATE TABLE IF NOT EXISTS `films` (
`movie_id` int(4) NOT NULL AUTO_INCREMENT,
`movie_title` varchar(100) NOT NULL,
`actor` varchar(100) NOT NULL,
`rating` varchar(20) NOT NULL,
`user_id` int(100) NOT NULL,
PRIMARY KEY (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `films` (`movie_id`, `movie_title`, `actor`, `rating`, `user_id`) VALUES
(1, 'batman', 'christian bale', 'Excellent', 3),
(2, 'Bne', 'reee', 'Ok', 3),
(3, 'Today', 'dd', 'Fair', 3);
表reviewed
的表结构
CREATE TABLE IF NOT EXISTS `reviewed` (
`review_id` int(4) NOT NULL AUTO_INCREMENT,
`review` mediumtext NOT NULL,
`movie_id` int(4) NOT NULL,
PRIMARY KEY (`review_id`),
KEY `movie_id` (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `reviewed` (`review_id`, `review`, `movie_id`) VALUES
(1, 'Wicked film', 1),
(2, 'gedtg', 2),
(3, 'dddd', 3);
表users
的表结构
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(4) NOT NULL AUTO_INCREMENT,
`email` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ;
INSERT INTO `users` (`user_id`, `email`, `password`, `name`) VALUES
(1, 'ben@talktalk.net', 'password', 'Ben'),
(2, 'richard@talk.net', '1', 'richard'),
答案 0 :(得分:2)
试试这个:
SELECT films.movie_title, films.rating, films.actor, reviewed.review, users.name
FROM films
LEFT JOIN reviewed ON films.movie_id=reviewed.movie_id
LEFT JOIN users ON films.user_id=users.user_id
答案 1 :(得分:1)
您是否可能希望在评论表中使用user_id? 那样你就有了以下内容:
评论表现在会有评分,评论本身,用户ID,电影ID和唯一评论ID。
这样一来,蝙蝠侠可以获得我的优秀评分和平均评分,而不会重复电影。
要修复上述查询,您可以使用以下内容:
SELECT films.movie_title, films.rating, films.actor, reviewed.review, users.name FROM films, reviewed, users WHERE films.movie_id = reviewed.movie_id AND films.user_id = users.user_id;
答案 2 :(得分:0)
如果您只想打印带评论的电影,则不需要OUTER JOIN。
SELECT films.movie_title, films.rating, films.actor, reviewed.review users.name
FROM films JOIN reviewed on films.movie_id=reviewed.movie_id
JOIN users ON films.user_id=users.user_id;
如果您想要打印所有电影,即使是那些评论为0的电影,您也必须使用LEFT JOIN(MySQL没有FULL OUTER JOIN)。
SELECT films.movie_title, films.rating, films.actor, reviewed.review users.name
FROM films LEFT JOIN reviewed on films.movie_id=reviewed.movie_id
LEFT JOIN users ON films.user_id=users.user_id;