SQL / MYSQL:一个查询中的两个语句

时间:2015-11-24 07:15:53

标签: mysql sql mysqli

film_actor,就像这样:

╔═════════╦══════╗
║ film_id ║ Task ║
╠═════════╬══════╣
║    1    ║ 162  ║
║    1    ║ 15   ║
║    1    ║ 20   ║
║    2    ║ 162  ║
║    2    ║ 12   ║
╚═════════╩══════╝

比以下查询:

SELECT film_id
FROM film_actor
WHERE actor_id LIKE '162'

结果:

1
2

下一个查询:

SELECT DISTINCT actor_id
FROM film_actor
WHERE film_id LIKE 'results from the query above'

结果应如下所示:

15
20
12

如何将这两个查询放在一起? 第一个的结果不应该显示,它只是最后和最终查询所需要的。

4 个答案:

答案 0 :(得分:4)

使用IN运算符:

SELECT DISTINCT actor_id
FROM film_actor
WHERE film_id in(SELECT film_id
                 FROM film_actor
                 WHERE actor_id LIKE '162')

JOIN

SELECT DISTINCT f2.actor_id
FROM film_actor f1
JOIN film_actor f2 ON f1.film_id = f2.film_id
WHERE f1.actor_id LIKE '162'

答案 1 :(得分:2)

SELECT DISTINCT actor_id
FROM film_actor
WHERE film_id IN
(
    SELECT film_id
    FROM film_actor
    WHERE actor_id LIKE '162'
)

答案 2 :(得分:1)

多数民众赞成

SELECT DISTINCT actor_id
FROM film_actor
WHERE film_id in (
  SELECT film_id
  FROM film_actor
  WHERE actor_id LIKE '162'
);

答案 3 :(得分:0)

你在寻找什么是subquery。你的应该是这样的:

{{1}}