我正在尝试创建一个以超过X种语言制作电影的演员排名,这是我的架构:
actor( actorid, actorname)
act ( actoirid, movieid, as_character)
movie ( movieid, title, mvyear)
lang (movieid, lang)
这是我坚持的查询:
SELECT actorid, actorname, title, mvyear, as_character, lang
FROM actor NATURAL JOIN act NATURAL JOIN movies_slice NATURAL JOIN lang
WHERE actorid IN (
SELECT act.actorid FROM act NATURAL JOIN lang
GROUP BY (act.actorid) HAVING COUNT(DISTINCT lang.lang) > $X$
ORDER BY COUNT(DISTINCT lang.lang) DESC --<<< Want to keep this order.
)
我知道IN运算符右侧的子查询的顺序被丢弃了。我该如何解决这个问题?
答案 0 :(得分:0)
永远不要使用NATURAL JOIN
。这是一个等待发生的错误。连接键是匹配的任何列名称 - 它甚至不遵循声明的外键关系。并且,查询很难遵循,因为您不知道用于加入的键。
然后,要执行您想要的操作,请将子查询移动到FROM
子句,将计数计算为字段,然后按顺序执行:
SELECT a.actorid, a.actorname, m.title, m.mvyear, act.as_character, l.lang
FROM actor a JOIN
act
USING (actorid) JOIN
movies m
USING (movieid) JOIN
lang l
USING (movieid) JOIN
(SELECT act.actorid, COUNT(DISTINCT l.lang) as numlangs
FROM act JOIN
lang l
USING (movieid)
GROUP BY act.actorid
HAVING COUNT(DISTINCT l.lang) > $X$
) al
USING (actorid)
ORDER BY al.numlangs DESC;