mysql使用没有连接的子查询

时间:2018-11-22 17:41:38

标签: mysql join subquery

这是相关表格

movie(id, title, relYear, category, runTime, director,
studioName, description, rating)

actor(aID, fName, surname, gender)

stars(movieID, actorID)

movGenre(movieID, genre) 

我只是想返回使用子查询“ Michael Fassbender”担任主角的电影...如果是这种情况,电影中的“ id”是指电影ID,而不是演员ID。我可以做

SELECT title, category
FROM movie 
WHERE 'id' =(SELECT 'aID'
             FROM actor
             WHERE fName='Michael' and surname='Fassbender')

有没有一种方法可以不使用任何联接?

2 个答案:

答案 0 :(得分:0)

您可以将Correlated SubqueryExists()一起使用

SELECT m.title, m.category
FROM movie AS m
WHERE EXISTS (SELECT 1
              FROM stars AS s 
              JOIN actor AS a ON a.aID = s.actorID
              WHERE a.fName = 'Michael' AND 
                    a.surname = 'Fassbender' AND
                    s.movieID = m.id)

以上解决方案仍以某种方式(在子查询中)利用JOIN。完全不使用Join的解决方案可以是:

SELECT title, category
FROM movie
WHERE id IN (SELECT movieID 
             FROM stars 
             WHERE actorID IN (SELECT aID 
                               FROM actor 
                               WHERE fName = 'Michael' AND 
                                     surname = 'Fassbender'))

PS 。除非这是一些技巧/硬件,否则我强烈建议不要在实际应用中使用此查询。

答案 1 :(得分:0)

SELECT DISTINCT m.title, m.category
FROM movie 
INNER JOIN stars s
ON s.movieID = m.id
INNER JOIN actors a
ON s.actorID = a.aID
   AND a.fName='Michael' 
   AND a.surname='Fassbender'