SQL:创建一个比较不同行的视图



我有电影的数据,看起来像这样:

cast_id | cast_name | movie_id
1         A           11
2         B           11
3         C           11
4         D           12
5         E           12
1         A           13

我想创建一个视图,比较两个不同的演员,这样我就可以从以下内容开始:

CREATE VIEW compare(cast_id_1, cast_id_2, num_movies);
SELECT * FROM compare LIMIT 1;
(1,2,2)

我看到的是演员A和演员B,他们两人总共有两部电影。

不知道如何比较这两个不同的行,到目前为止,我的搜索程序都没有成功。非常感谢您的帮助!

这是一个自联接:

create view myview as 
select t1.cast_id cast_id_1, t2.cast_id cast_id_2, count(*) num_movies
from mytable t1
inner join mytable t2 on t2.movie_id = t1.movie_id and t1.cast_id < t2.cast_id
group by t1.cast_id, t2.cast_id

Thives生成曾经出现在同一部电影中的所有演员组合,以及电影总数。联接条件CCD_;镜像;记录。

然后可以查询视图。如果你想要有两个常见电影的成员(这实际上没有显示在你的样本数据中…(:

select * from myview where num_movies = 2

我认为一个过程可能会有所帮助。这个存储过程将2个cast_id和num_movies作为输入参数。它选择两个cast_id一起出现的电影中的movie_id。然后,根据该数字是否超过num_movies参数:1(返回电影列表(上映日期、导演等(,否则返回消息"Were not in 2 movies together"。

drop proc if exists TwoMovieActors;
go
create proc TwoMovieActors
@cast_id_1    int,
@cast_id_2    int,
@num_movies   int
as
set nocount on;
declare         @m      table(movie_id      int unique not null,
rn            int not null);
declare         @rows   int;
with
cast_cte as (
select *, row_number() over (partition by movie_id order by cast_name) rn
from movie_casts mc
where cast_id in(@cast_id_1, @cast_id_2))
insert @m
select movie_id, row_number() over (order by movie_id) rn
from cast_cte
where rn=2
select @rows=@@rowcount;
if @rows<@num_movies
select concat('Were not in ', cast(@num_movies as varchar(11)), ' movies together');
else
select m.movie_id, mv.movie_name, mv.release_date, mv.director
from @m m
join movies mv on m.movie_id=mv.movie_id;

执行它就像

exec TwoMovieActors 1, 2, 2;

最新更新