MySQL SELECT 查询对许多唯一字段值具有限制


MySQL SELECT query with LIMIT on a number of unique field values

例如,我有两个表:文章和部分。

id   name        id  article_id    name       text
 1  article_1     1      1       section_1  some_text
 2  article_2     2      2<-     section_2  some_text
      ...         3      2<-     section_3  some_text
                  4      3       section_4  some_text
                                    ...

某些部分具有相同的article_ids。我需要一些 MySQL 查询,例如

"SELECT `text` FROM `sections` WHERE MATCH(`text`) AGAINST ('$str' IN BOOLEAN MODE) LIMIT UNIQUE(`article_id`, $count)"

或其他用于选择任意数量的字段的其他内容,这些字段总共不超过$count唯一article_ids。

我不太明白你想要什么,但看看这是否有帮助:

drop table sections;
create table sections (
    `name` varchar(255),
    `article_id` int,
    `section_name` varchar(255),
    `text` varchar(255)
);
insert into sections values ('article_1', 1, 'section_1', 'some_text');
insert into sections values ('article_2', 2, 'section_2', 'some_text');
insert into sections values ('article_2', 2, 'section_3', 'some_text');
insert into sections values ('article_3', 3, 'section_3', 'some_text');
insert into sections values ('article_4', 4, 'section_4', 'some_text');
SELECT `section_name` FROM `sections` group by `section_name` having count(distinct `article_id`) = 1;

查询返回不超过 1 篇文章中出现的所有部分。这是输出:

section_1
section_2
section_4

如您所见,section_3被排除在第2条和第3条中的结果之外。