简体   繁体   中英

MYSQL GROUP BY returns no results with FULLTEXT SEARCH

I have the following MYSQL schema:

CREATE TABLE IF NOT EXISTS `tag` (
   `id` SMALLINT UNSIGNED NOT NULL,
   `tag` VARCHAR(15) NOT NULL,
   FULLTEXT INDEX(`tag`),
   PRIMARY KEY (`id`,`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `tag`(`id`,`tag`) VALUES
('1','motor'),
('2','motor');

I want to select rows from tag table grouped by tag column. I ran the following command:

SELECT COUNT(id),tag FROM tag
GROUP BY tag

The expected result:

COUNT(id) | tag
------------------
    2     | motor

The actual result: no rows returned

If I remove the FullText Index from the table, the results return as expected. I don't know what is going wrong when using fulltext with group

Update With further research the problem seems to be from the composite primary key. If I switch to one-column primary key, query works again but I need to use a composite key for this table as the same id could have multiple tags.

I created an SQL fiddle for you to try: http://sqlfiddle.com/#!9/1f765d/1/0

Finally discovered the problem. The engine has 2 indices to choose from when executing the query, which ends up not using any at all and returning no results.

It's very likely that is a bug. This is a case where FORCE INDEX comes in handy as a workaround.

So the final working command:

SELECT COUNT(id),tag FROM tag
FORCE INDEX(PRIMARY)
GROUP BY tag

And this is a fiddle with the updated code: http://sqlfiddle.com/#!9/a8568/21/0

Thanks everyone!

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