简体   繁体   English

具有不同值的 SQL 查询

[英]SQL query with distinct values

I have the two following schemes:我有以下两个方案:

Movies[title, year, director, country, rating, genre, gross, producer]

and

Actors[title, year, characterName, actor]

Now I have the following exercise现在我有以下练习

Find character names that appeared in two movies produced in different countries.查找出现在不同国家制作的两部电影中的角色名称。

My idea was the following which doesn't really work:我的想法是以下实际上不起作用:

SELECT characterName
FROM Actors a
JOIN Movies m
ON a.title=m.title
AND a.year=m.year
WHERE COUNT(m.title)=2
AND COUNT(DISTINCT(m.country)=2
GROUP BY m.title;

My idea was to obviously select the characterName and join both tables on title and year because they are unique values in combination.我的想法是显然选择 characterName 并在标题和年份上加入两个表,因为它们是唯一的组合值。 Then my plan was to get the movies that are unique (by grouping them) and find the ones with a count of 2 since we want two movies.然后我的计划是获取唯一的电影(通过将它们分组)并找到计数为 2 的电影,因为我们想要两部电影。 I hope that I am right till now.我希望直到现在我都是对的。 Now I have my problems, because I don't really know how to evaluate if the movies played in two different locations.现在我遇到了问题,因为我真的不知道如何评估电影是否在两个不同的地点播放。 I want to somehow make sure that they play in different countries.我想以某种方式确保他们在不同的国家比赛。

You are on the right track.你走在正确的轨道上。 Here is a fixed version of your original query, that should get you the results that you expect:这是原始查询的固定版本,它应该会得到您期望的结果:

select a.characterName
from actors a
inner join movies m 
    on  m.title = a.title
    and m.year = a.year
group by a.characterName
having count(distinct m.coutry) >= 2

Notes on your design:设计注意事项:

  • it seems like you are using (title, year) as the primary key for the movies table.似乎您正在使用(title, year)作为movies表的主键。 This does not look like a good design (what if two movies with the same title are produced the same year?).这看起来不是一个好的设计(如果两部同名电影是同一年制作的呢?)。 You would be better off with an identity column (in MySQL, an autoincremented primary key), that you would refer as a foreign key in the actors table您最好使用标识列(在 MySQL 中,自动递增的主键),您可以将其作为actors表中的外键

  • better yet, you would probably need to create a separate table to store the masterdata of the actors, and set up a junction table, say appearances , that represents which actors interpreted which character in which movie更好的是,您可能需要创建一个单独的表来存储演员的主数据,并设置一个连接表,比如appearances ,表示哪个演员解释了哪部电影中的哪个角色

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

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