简体   繁体   中英

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

For example, I have two tables: articles and sections.

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
                                    ...

Some sections have identical article_ids. I need some MySQL query, such as

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

or something else for select any number of fields that in total have not more than $count unique article_ids.

I don't quite understand what is it that you want, but see if this helps:

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;

The query returns all sections that appear in no more then 1 article. Here is the output:

section_1
section_2
section_4

As you can see., section_3 was excluded from the result as it appears in both article 2 and 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM