gpt4 book ai didi

mysql - SQL:请改进我的 select-where-subquery-returns-one 查询

转载 作者:行者123 更新时间:2023-11-29 01:44:59 26 4
gpt4 key购买 nike

我已经有了解决以下问题的有效解决方案,但我担心它很愚蠢或效率低下。

有一个 Thing 表包含 (id, attributes...) 列,还有一个 ThingVersion 表包含 ( id, thing_id, version_attributes...) 问题是从 Thing 中选择一个对应的 ThingVersion 行。

目前我有类似的东西

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_idThingVersion.thing_id 中的每个值都肯定出现在 Thing.id 中。 )

关于mysql - SQL:请改进我的 select-where-subquery-returns-one 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9435525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com