我有数据库,可以对电影和演员进行评分。我需要选择电影的标题和所有这些演员。我创建下一个查询:
SELECT movies.title, CONCAT_WS(' ', actors.name, actors.surname) as Actor FROM movies LEFT JOIN movies_actors
ON movies.id = movies_actors.movie_id
LEFT JOIN actors
ON actors.id = movies_actors.actor_id
我得到了一些东西:
+------------------------------+--------------+
| title | actor |
+------------------------------+--------------+
| Sin City: A Dame to Kill For | Eva Green |
| Sin City: A Dame to Kill For | Bruce Willis |
+------------------------------+--------------+
但我希望得到一些东西:
+------------------------------+--------------+
| title | actor |
+------------------------------+--------------+
| Sin City: A Dame to Kill For | Eva Green |
| | Bruce Willis |
+------------------------------+--------------+
我尝试使用
SELECT DISTINCT movies.title...
但它没有帮助。
你能帮帮我吗?谢谢! 这是我的数据库CREATE TABLE movies (
id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255),
director VARCHAR(255),
created DATE,
budget DECIMAL(12,2),
box_office DECIMAL(13,2),
duration TIME
)
CREATE TABLE actors (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
surname VARCHAR(255),
name VARCHAR(255),
birthday DATE
)
ALTER TABLE movies_actors
ADD FOREIGN KEY (movie_id) REFERENCES movies (id)
ALTER TABLE movies_actors
ADD FOREIGN KEY FOREIGN KEY (actor_id) REFERENCES actors (id)
INSERT INTO 'movies'
(`id`, `title`, `director`, `created`, `budget`, `box_office`, `duration`)
VALUES
(1, 'Sin City: A Dame to Kill For', 'Frank Miller, Robert Anthony Rodriguez', '2014', 62000000.00, 38000000.00, '01:42:00')
INSERT INTO `actors`
(`id`, `surname`, `name`, `birthday`)
VALUES
(1, 'Green', 'Eva', '1980-07-06'),
(2, 'Willis', 'Bruce', '1955-03-19')
答案 0 :(得分:0)
GROUP_CONCAT()
SELECT movies.title,
GROUP_CONCAT(concat(actors.name, ' ', actors.surname)) as Actors
FROM movies
LEFT JOIN movies_actors ON movies.id = movies_actors.movie_id
LEFT JOIN actors ON actors.id = movies_actors.actor_id
GROUP BY movies.title
答案 1 :(得分:0)
加入后,如果有有效值,则始终会获得foreach列单元格的结果。因此,当您在联接中找到2个有效的演员时,标题将重复2次,正如您已经注意到的那样。
+------------------------------+--------------+
| title | actor |
+------------------------------+--------------+
| Sin City: A Dame to Kill For | Eva Green |
| Sin City: A Dame to Kill For | Bruce Willis |
+------------------------------+--------------+
你可以通过标题ofc连接演员和小组的结果,得到这样的结果:
+------------------------------+-------------------------+
| title | actor |
+------------------------------+-------------------------+
| Sin City: A Dame to Kill For | Eva Green,Bruce Willis |
+------------------------------+-------------------------+
SELECT
movies.title,
GROUP_CONCAT(concat(actors.name, ' ', actors.surname)) as Actor
FROM
movies
LEFT JOIN
movies_actors ON movies.id = movies_actors.movie_id
LEFT JOIN
actors ON actors.id = movies_actors.actor_id
GROUP BY movies.title