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

标签 mysql sql mysql5

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

有一个 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_idThingVersion.thing_id 中出现的每个值都必须出现 Thing.id。 )

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

相关文章:

php - 使用 mySQL 和 PHP 每 5 秒更新一次 HTML 表?

Java 或 SQL 在数组中添加缺失的月份

SQL全选并更改一列的格式

sql - 死锁 - 没有数据时锁定列

MySQL 新关键字

Mysql insert with set 和 select

php - 如何解决这个问题:“警告:mysql_num_rows()期望参数1是资源,//中给出的 bool 值”?

MySql:每个 id 的位置

带 "default values"的 SQL GROUP BY

mysql - Sql 查询 对于我的案例