我有两个具有 1:n 关系的表:“内容”和“版本化内容数据”(例如,文章实体和该文章创建的所有版本)。我想创建一个显示每个“内容”的顶级版本的视图。

目前我使用这个查询(带有一个简单的子查询):

SELECT 
   t1.id, 
   t1.title, 
   t1.contenttext,
   t1.fk_idothertable
   t1.version
FROM mytable as t1
WHERE (version = (SELECT MAX(version) AS topversion
                  FROM mytable
                  WHERE (fk_idothertable = t1.fk_idothertable)))

子查询实际上是对同一个表的查询,提取特定项的最高版本。请注意,版本化项目将具有相同的 fk_idothertable。

在 SQL Server 中我尝试创建一个 索引视图 这个查询,但似乎我不能,因为子查询不允许 索引视图. 。所以...这是我的问题...您能想出一种方法将此查询转换为某种带有 JOIN 的查询吗?

索引视图似乎不能包含:

  • 子查询
  • 公用表表达式
  • 派生表
  • HAVING 子句

我很绝望。欢迎任何其他想法:-)

多谢!

有帮助吗?

解决方案

如果表已经在生产中,这可能不会有帮助,但对此进行建模的正确方法是使 version = 0 成为永久版本,并始终增加旧材料的版本。因此,当您插入新版本时,您会说:

UPDATE thetable SET version = version + 1 WHERE id = :id
INSERT INTO thetable (id, version, title, ...) VALUES (:id, 0, :title, ...)

那么这个查询就只是

SELECT id, title, ... FROM thetable WHERE version = 0

没有子查询,没有 MAX 聚合。您始终知道当前版本是什么。您不必选择 max(version) 即可插入新记录。

其他提示

也许是这样的?

SELECT
  t2.id,
  t2.title,
  t2.contenttext,
  t2.fk_idothertable,
  t2.version
FROM mytable t1, mytable t2
WHERE t1.fk_idothertable == t2.fk_idothertable
GROUP BY t2.fk_idothertable, t2.version
HAVING t2.version=MAX(t1.version)

只是一个疯狂的猜测...

您也许可以将 MAX 设置为进行分组依据的表别名。

它可能看起来像这样:

SELECT 
   t1.id, 
   t1.title, 
   t1.contenttext,
   t1.fk_idothertable
   t1.version
FROM mytable as t1 JOIN
   (SELECT fk_idothertable, MAX(version) AS topversion
   FROM mytable
   GROUP BY fk_idothertable) as t2
ON t1.version = t2.topversion

我认为 FerranB 很接近,但分组不太正确:

with
latest_versions as (
   select 
      max(version) as latest_version,
      fk_idothertable
   from 
      mytable
   group by 
      fk_idothertable
)
select
  t1.id, 
  t1.title, 
  t1.contenttext,
  t1.fk_idothertable,
  t1.version
from 
   mytable as t1
   join latest_versions on (t1.version = latest_versions.latest_version 
      and t1.fk_idothertable = latest_versions.fk_idothertable);

中号

If SQL Server accepts LIMIT clause, I think the following should work:
SELECT 
   t1.id, 
   t1.title, 
   t1.contenttext,
   t1.fk_idothertable
   t1.version
FROM mytable as t1 ordery by t1.version DESC LIMIT 1;
(DESC - For descending sort; LIMIT 1 chooses only the first row and
DBMS usually does good optimization on seeing LIMIT).

我不知道这会有多有效,但是:

SELECT t1.*, t2.version
FROM mytable AS t1
    JOIN (
        SElECT mytable.fk_idothertable, MAX(mytable.version) AS version
        FROM mytable
    ) t2 ON t1.fk_idothertable = t2.fk_idothertable

像这样...我假设子查询中的“mytable”是一个不同的实际表...所以我将其称为 mytable2。如果是同一个表,那么这仍然有效,但我想 fk_idothertable 将只是“id”。


SELECT 
   t1.id, 
   t1.title, 
   t1.contenttext,
   t1.fk_idothertable
   t1.version
FROM mytable as t1
    INNER JOIN (SELECT MAX(Version) AS topversion,fk_idothertable FROM mytable2 GROUP BY fk_idothertable) t2
        ON t1.id = t2.fk_idothertable AND t1.version = t2.topversion

希望这可以帮助

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top