Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL:创建一个比较不同行的视图_Sql_Join_Count_Sql View - Fatal编程技术网

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

SQL:创建一个比较不同行的视图,sql,join,count,sql-view,Sql,Join,Count,Sql View,我有这样一些电影的数据: 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);

我有这样一些电影的数据:

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)
我想创建一个视图,在该视图中比较两个不同的演员阵容成员,以便从以下内容开始:

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

我想做个手术可能会有帮助。此存储过程将2个cast_id和num_电影作为输入参数。它选择两位演员同时出演的电影的电影id。然后根据该数字是否超过num_movies参数:1)返回电影列表(发行日期、导演等),否则返回消息“两部电影不在一起”

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;

你的数据库管理系统是什么?