根据多个表的连接显示条件为真

问题描述

背景

我想向所有与演员本·阿弗莱克(Ben Affleck)合作的人们展示。

这是我的数据:

  People table
  
  id    name
 
  1     Ben Affleck
  2     Leonardio DiCaprio
  3     Matt Damon


  Movies table

  id   title
  1    Good Will Hunting
  2    example
  3    example


  Credits table
 
  id  movie_id person_id 
 
  1   1        1
  2   2        4
  3   3        6

所需的输出

 name         movie
 
 Matt Damon   Good Will Hunting
 

这是我尝试过的:

我知道我必须将People,Movies和Credits表一起加入,因为我想找到与Ben Affleck合作的所有演员:

 SELECT p.name,m.title,c.movie_id
 FROM Credits c
 JOIN People p ON p.id = c.person_id
 JOIN Movies m ON m.id = p.id
 WHERE p.name = 'Ben Affleck';

我还在对此进行研究。

解决方法

您可以使用exists

select p.name,m.title,c.movie_id
from people p
inner join credits c on c.person_id = p.id
inner join movies m on m.id = c.movie_id
where exists (
    select 1 
    from people p1
    inner join credits c1 on c1.person_id = p1.id
    where c1.movie_id = c.movie_id and p1.name = 'Ben Affleck'
)
,

或者您可以使用IN,有时它比EXISTS更易于理解。您在初始查询中加入Movies表时也出错,您必须比较Movies中的电影ID(idCredits中的电影ID({{ 1}}

movie_id
,

您可以使用IN子句,但也不需要显示Ben Affleck

 SELECT 
    p.name,c.movie_id
FROM
    Credits c
        JOIN
    People p ON p.id = c.person_id
        JOIN
    Movies m ON m.id = p.id
WHERE
    m.id IN (SELECT 
            movie_id
        FROM
            credis
        WHERE
            person_id IN (SELECT 
                    id
                FROM
                    People
                WHERE
                    name = 'Ben Affleck'))
    AND p.name <> 'Ben Affleck'

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...