mysql - sql 我如何选择 Actor 和制片人

标签 mysql sql

大家。 我是 sql 新手,只是想知道如何通过一项选择从表中选择所有具有两种职业的 id_people。

我的 table 是这样的

CREATE TABLE `films_peoples_prof` (
  `id_film` int(11) NOT NULL,
  `id_people` int(11) NOT NULL,
  `id_profession` int(11) NOT NULL,
  PRIMARY KEY (`id_film`,`id_people`,`id_profession`),
  KEY `id_people` (`id_people`),
  KEY `id_profession` (`id_profession`),
  CONSTRAINT `films_peoples_prof_ibfk_1` FOREIGN KEY (`id_film`) REFERENCES `films` (`id`) ON DELETE CASCADE,
  CONSTRAINT `films_peoples_prof_ibfk_2` FOREIGN KEY (`id_people`) REFERENCES `peoples` (`id`) ON DELETE CASCADE,
  CONSTRAINT `films_peoples_prof_ibfk_3` FOREIGN KEY (`id_profession`) REFERENCES `professions` (`id`) ON DELETE CASCADE
)


+---------+-----------+---------------+
| id_film | id_people | id_profession |
+---------+-----------+---------------+
|       4 |         1 |             1 |
|       4 |         1 |             2 |
|       5 |         1 |             1 |
|       7 |         1 |             1 |
|       4 |         2 |             1 |
|       4 |         3 |             1 |
|       5 |         3 |             1 |
|       6 |         3 |             1 |
|       4 |         4 |             1 |
|       8 |         5 |             1 |
|       9 |         5 |             1 |
|       4 |         6 |             1 |
|       4 |         6 |             2 |
|       9 |         7 |             2 |
|       4 |        10 |             1 |
+---------+-----------+---------------+

id = 1 - Actor ,id = 2 - 制片人 在这种情况下结果应该是 1 , 6

最佳答案

您需要使用group by,例如

select id_people 
from films_peoples_prof
where id_profession in (1,2)
group by id_people 
having count(distinct id_profession ) = 2;

关于mysql - sql 我如何选择 Actor 和制片人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44521555/

相关文章:

php - 按年份在存档小部件中分组存档并按特定月份分隔

php - 如何将列数据转换为行数据

sql - 有没有办法让 SSMS 每次打开时都打开某个连接?

sql - 关于如何读取SQL执行计划的问题

sql - 重组 Postgrest 查询

php - session 的sql注入(inject)

sql - 使用 hibernateTemplate、JdbcTemplate 进行 Spring 批量插入

mysql - sql数据库中列值的多表约束

mysql - 如何选择不同行的两个字段?

java - 在 Spring Boot 中实例化的类中的 Autowiring 存储库