2017-04-11 60 views
0

比方說這是我的表:如何找到在mysql中有2個actor的電影標題?

************ 
* film  * 
************  
* title * 
* film_id * 
************ 

************  
* actors * 
************ 
* film_id * 
* actor_id * 
************ 

我想在其中找到兩個演員參與actor_id = 22 and actor_id = 23 如何編寫查詢的影片的片名?

我想:

SELECT title 
FROM film 
WHERE film_id IN(
    SELECT film_id, COUNT(*) 
    FROM actors 
    WHERE actor_id=22 OR actor_id=23 
    GROUP BY film_id) 

回答

0

我相信下面的查詢應該給你做。

SELECT title 
FROM film f, actors a1, actors a2 
WHERE f.film_id=a1.film_id AND a1.actor_id=22 
     AND f.film_id=a2.film_id AND a2.actor_id=23; 

加入也是一個更好的方式來處理:

SELECT title 
FROM film f 
JOIN actors a1 ON f.film_id = a1.film_id 
JOIN actors a2 ON f.film_id = a2.film_id 
WHERE a1.actor_id = 22 
     AND a2.actor_id = 23; 
0

如果內部加入到演員表的兩倍,並設置個人actor_id在每個標準加入它需要兩個演員是在電影裏。因此你只會返回有兩個演員的電影。

SELECT film.title 
FROM film 
INNER JOIN actors actors1 
    ON film.film_id = actors1.film_id 
    AND actors1.actor_id=22 
INNER JOIN actors actors2 
    ON film.film_id = actors2.film_id 
    AND actors2.actor_id=23 
GROUP BY film.title 
相關問題