MySQL/MariaDB - 在不丢失任何主 ID 的情况下加入 LIMIT 个查询结果

MySQL/MariaDB - LIMIT joined query result while not losing any primary ID

我知道如何使用 LIMIT a,b 限制查询结果,但是如果我想 LIMIT 使用 JOIN 创建的查询,该查询有多行一个主 ID 而每个 ID 至少保留一行?

让我解释更多...*
我有 table 个 post 类别,然后有 table 个类别。
一个 post,但是,可以在更多类别中。
当我查询 post 时,我也想同时查询它们的类别...
...问题是我最多只需要 1 个类别。每 1 post 个结果(我不在乎是哪个)

当前(示例性)结果

ID   | title       | content | category_ID | category_name
1    | First Post  | ....... |   2         | Boring Articles
1    | First Post  | ....... |   5         | Interesting Articles
1    | First Post  | ....... |   1         | Mojo Tips
2    | Second Post | ....... |   5         | Interesting Articles
3    | Third Post  | ....... |   5         | Interesting Articles
3    | Third Post  | ....... |   4         | Fitness
4    | Fourth Post | ....... |   NULL      | NULL

期望的(示例)结果 - 请注意每个 post ID 至少保留一行!

ID   | title       | content | category_ID | category_name
1    | First Post  | ....... |   2         | Boring Articles
2    | Second Post | ....... |   5         | Interesting Articles
3    | Third Post  | ....... |   5         | Interesting Articles
4    | Fourth Post | ....... |   NULL      | NULL

但如果我只做某事,比如

SELECT * FROM posts
LEFT JOIN relationships USING(ID)
LEFT JOIN categories USING(category_ID)
LIMIT 0,4

这会发生(丢失需要的数据 - 不再是每 1 个 ID 1 行...):

ID   | title       | content | category_ID | category_name
1    | First Post  | ....... |   2         | Boring Articles
1    | First Post  | ....... |   5         | Interesting Articles
1    | First Post  | ....... |   1         | Mojo Tips
2    | Second Post | ....... |   5         | Interesting Articles

PS:我想知道如何在 MySQL/MariaDB 中解决这个问题,如果在使用一个或另一个时这样做有什么不同 - 请问有什么不同? :)

一种方法使用子查询:

SELECT p.*,
       (SELECT c.category_name
        FROM relationships r JOIN
             categories c
             USING (category_ID)
       WHERE r.id = p.id
       LIMIT 1
      ) as category_name
FROM posts p
LIMIT 0, 4;

注意:使用 LIMIT 时通常会有 ORDER BY

另一种方法使用GROUP BY:

SELECT p.*, c.*
FROM posts p LEFT JOIN
     relationships r
     USING (ID) LEFT JOIN
     categories c
     USING (category_ID)
GROUP BY p.id
LIMIT 0, 4;

我不喜欢这样使用 GROUP BY,但它是一个有效的 MySQL 扩展。