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

SQL: create a view comparing different rows

我有这样的电影数据:

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,他们两人一共拍了2部电影。

不确定如何比较两个不同的行,到目前为止我的搜索器没有成功。非常感谢任何帮助!

那是 self-join:

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 生成曾经出现在同一部电影中的演员的所有组合,以及电影总数。加入条件 t1.cast_id < t2.cast_id 是为了避免“镜像”记录。

然后您可以查询该视图。如果您想要拥有两部共同电影的成员(实际上没有显示在您的示例数据中...):

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;