1

我有三张桌子。

 Page                           Revision                                   Text                       
 +-----------+-------------+    +-----------+-------------+----------+     +-------------+---------+
 | page_id   | rev_id      |    | rev _id   | rev_text_id | page_id  |     | rev_text_id | text    |
 +-----------+-------------+    +-----------+-------------+----------+     +-------------+---------+
 |      1    |     2       |    |      1    |     1       |    1     |     |      1      |     A   |
 +--------------------------    +------------------------------------+     +-----------------------+
 |      2    |     5       |    |      2    |     2       |    1     |     |      2      |     B   |
 +-------------------------+    +------------------------------------+     +-----------------------+
                                |      3    |     3       |    2     |     |      3      |     C   |
                                +------------------------------------+     +-----------------------+
                                |      4    |     4       |    2     |     |      4      |     D   |
                                +------------------------------------+     +-----------------------+
                                |      5    |     4       |    2     |               
                                +------------------------------------+               

我想要的输出是:

 +--------+-------------+
 | rev_id | rev_text_id |
 +--------+-------------+
 |   1    |      1      |
 +----------------------+
 |   3    |      3      |
 +----------------------+
 |   4    |             |
 +----------------------+

我的目标是找到可以在单个查询中从每个表中删除的 rev_id 和 rev_text_id。由于修订表可以为多个修订保留相同的 rev_text_id,因此我需要排除每个页面最高的 rev_text_id(在示例 4 中为第 2 页)。

我开始涉足以下方面:

 SELECT
 r.rev_id,r.rev_text_id
 FROM revision r, page p, text t
 WHERE p.page_id = r.page_id
 AND t.rev_text_id = r.rev_text_id 
 AND p.rev_id != r.rev_id
 AND r.rev_text_id not in (
      SELECT max(r.rev_text_id)
      FROM revision AS r, page AS p
      WHERE r.rev_id = p.rev_id
 );

但这会在我想要的输出中跳过 rev_id 4 的记录,并且不包括“空案例”..

4

1 回答 1

0

尝试这个:

SELECT r.`rev_id`, r.`rev_text_id`
FROM `Revision` AS r
WHERE r.`rev_text_id` NOT IN (SELECT r.`rev_text_id`
                              FROM `Revision` AS r, `Page` AS p
                              WHERE r.`rev_id` = p.`page_latest`;)
ORDER BY r.`rev_id`;

这基本上抓取了等于 page_latest 的 rev_id,找到与那些 rev_id 相关联的 rev_text_id,并使用那些 rev_text_id 作为过滤器。

于 2013-11-12T15:02:51.323 回答