如何结合两种情况在MYSQL中选择结果?

时间:2019-07-15 18:06:27

标签: mysql sql

我正在尝试查询以下情况

鉴于DVD Rental示例数据库中的film_actor和电影表,可以找到Sidney Crowe(actor_id = 105)和Salma Nolte(actor_id = 122)一起放映的所有电影,并按字母顺序排列结果集。

**film schema**
 Column     | Type                        | Modifiers
------------+-----------------------------+----------
title       | character varying(255)      | not null
film_id     | smallint                    | not null

**film_actor schema** 
Column     | Type                        | Modifiers
------------+-----------------------------+----------
actor_id    | smallint                    | not null
film_id     | smallint                    | not null
last_update | timestamp without time zone | not null

我无法理解如何编写查询,其中结果将显示两个演员共同工作过的电影标题。

SELECT f.title AS title FROM film f INNER JOIN film_actor fa ON f.film_id = fa.film_id WHERE fa.actor_id IN(102, 122) ORDER BY title;

我尝试了此查询,但未获得预期的结果,而是返回了结果两个演员之一是电影的一部分。但是,我希望结果两个演员共同努力而不是一个个

2 个答案:

答案 0 :(得分:1)

通过将film_actor表中的film_id分组并在HAVING子句中设置条件,可以获得两个演员的所有电影ID:

SELECT film_id 
FROM film_actor
WHERE actor_id IN (102, 122)
GROUP BY film_id
HAVING COUNT(DISTINCT actor_id) = 2 

最后使用此查询获取电影标题:

SELECT title 
FROM film
WHERE film_id IN (
    SELECT film_id 
    FROM film_actor
    WHERE actor_id IN (102, 122)
    GROUP BY film_id
    HAVING COUNT(DISTINCT actor_id) = 2 
)
ORDER BY title

获得相同结果的另一种方法是使用EXISTS(两次):

SELECT f.title
FROM film f 
WHERE 
  EXISTS(
    SELECT 1 FROM film_actor
    WHERE film_id = f.film_id AND actor_id = 102 
  )
  AND
  EXISTS(
    SELECT 1 FROM film_actor
    WHERE film_id = f.film_id AND actor_id = 122 
  )
ORDER BY f.title

答案 1 :(得分:1)

这是自我加入的经典示例。基本上,您可以将film表与film_actor表连接两次。一次给演员105,第二次给演员122。如果使用这种方法,查询将如下所示:

select f.* from film f INNER JOIN film_actor fa105 ON f.film_id = fa105.film_id and fa105.actor_id = 105
INNER JOIN film_actor fa122 ON f.film_id = fa122.film_id and fa122.actor_id = 122 ORDER by f.title

另一种方法是编写嵌套查询,但是这种方法对我来说更干净。