我已经有了解决以下问题的有效解决方案,但我担心它很愚蠢或效率低下。
有一个 Thing
表,其中包含 (id, attribute...)
列,还有一个 ThingVersion
表,其中包含 ( id、thing_id、version_attributes...)
问题是从恰好存在一个对应的 ThingVersion
行的 Thing
中进行选择。
目前我有类似的东西
SELECT Thing.id AS id, Foo.whatever
FROM Thing JOIN Foo ON Thing.id=Foo.thing_id
WHERE Thing.id IN (
SELECT thing_id FROM ThingVersion TV
WHERE 1 = (
SELECT COUNT(*)
FROM ThingVersion TV2
WHERE TV2.thing_id = TV.thing_id)
)
ORDER BY Foo.whatever
它似乎给出了正确的结果,并且作为一个强调的非大师,它似乎是不言自明的,但是 - 三个 选择?!?! -- 我不禁觉得一定有更好的方法。
有吗?
最佳答案
您可以在子查询中使用 HAVING
子句:
SELECT Thing.id AS id, Foo.whatever
FROM Thing JOIN Foo ON Thing.id=Foo.thing_id
WHERE Thing.id IN
( SELECT thing_id
FROM ThingVersion TV
GROUP BY thing_id
HAVING COUNT(*) = 1
)
ORDER BY Foo.whatever
;
您还可以消除主查询中的JOIN
:
SELECT thing_id AS id, whatever
FROM Foo
WHERE thing_id IN
( SELECT thing_id
FROM ThingVersion TV
GROUP BY thing_id
HAVING COUNT(*) = 1
)
ORDER BY whatever
;
(我假设 Foo.thing_id
和 ThingVersion.thing_id
中出现的每个值都必须出现 Thing.id
。 )
关于mysql - SQL:请改进我的 select-where-subquery-returns-one 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9435525/