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

时间:2012-02-24 17:48:56

标签: mysql sql mysql5

我已经找到了解决以下问题的有效方案,但我担心这是愚蠢或低效的。

有一个Thing表格,列(id, attributes...)以及ThingVersion表格,列(id, thing_id, version_attributes...)问题是从Thing中选择一个对应的列<{1}}行存在。

目前我有类似

的东西
ThingVersion

它似乎给出了正确的结果,并且作为一个强调非大师似乎不言自明,但是 - 三个选择?!?! - 我不禁觉得必须有更好的方法。

有吗?

3 个答案:

答案 0 :(得分:2)

您可以在子查询中使用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。)

答案 1 :(得分:1)

SELECT Thing.id AS id, Foo.whatever
FROM Thing JOIN Foo ON Thing.id=Foo.thing_id
where Thing.idin (select thing_id from ThingVersion group by thing_id having COUNT(*)>1)

答案 2 :(得分:1)

严格使用JOIN的解决方案:

SELECT t.*
FROM Thing t
JOIN ThingVersion tv1
  ON tv1.thing_id = t.id
LEFT JOIN ThingVersion tv2
  ON tv2.thing_id = t.id
  AND tv2.id <> tv1.id
WHERE tv2.id IS NULL

使用GROUP BY和COUNT的解决方案:

SELECT t.* 
FROM Thing t
JOIN ThingVersion tv
  ON tv.thing_id = t.id
GROUP BY t.id
HAVING COUNT(t.id) = 1;

尝试将它们都用于表现。