-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12.sql
More file actions
80 lines (62 loc) · 2.17 KB
/
12.sql
File metadata and controls
80 lines (62 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
-- In 12.sql, write a SQL query to list the titles of all movies in which both Bradley Cooper and Jennifer Lawrence starred.
-- Your query should output a table with a single column for the title of each movie.
-- You may assume that there is only one person in the database with the name Bradley Cooper.
-- You may assume that there is only one person in the database with the name Jennifer Lawrence.
select movies.title
from people
join stars on stars.person_id = people.id
join movies on movies.id = stars.movie_id
where people.name in ('Jennifer Lawrence', 'Bradley Cooper');
select movies.title
from people
join stars on stars.person_id = people.id
join movies on movies.id = stars.movie_id
where people.name = 'Jennifer Lawrence'
INTERSECT
select movies.title
from people
join stars on stars.person_id = people.id
join movies on movies.id = stars.movie_id
where people.name = 'Bradley Cooper';
SELECT title
FROM movies
JOIN stars AS s1 ON movies.id = s1.movie_id
JOIN people AS p1 ON s1.person_id = p1.id
JOIN stars AS s2 ON movies.id = s2.movie_id
JOIN people AS p2 ON s2.person_id = p2.id
WHERE p1.name = 'Bradley Cooper'
AND p2.name = 'Jennifer Lawrence';
--subquery with in used
SELECT movies.title
FROM movies
JOIN stars ON movies.id = stars.movie_id
JOIN people ON stars.person_id = people.id
WHERE people.name = 'Bradley Cooper'
AND movies.id IN (
SELECT movies.id
FROM movies
JOIN stars ON movies.id = stars.movie_id
JOIN people ON stars.person_id = people.id
WHERE people.name = 'Jennifer Lawrence'
);
-- my subquery with in used
select movies.title
from people
join stars on stars.person_id = people.id
join movies on movies.id = stars.movie_id
where people.name = 'Bradley Cooper'
AND movies.id IN (
SELECT movies.id
FROM movies
JOIN stars ON movies.id = stars.movie_id
JOIN people ON stars.person_id = people.id
WHERE people.name = 'Jennifer Lawrence'
);
--Join + group by approaach:
SELECT movies.title
FROM movies
JOIN stars ON movies.id = stars.movie_id
JOIN people ON stars.person_id = people.id
WHERE people.name IN ('Bradley Cooper', 'Jennifer Lawrence')
GROUP BY movies.title
HAVING COUNT(DISTINCT people.name) = 2;