搜索以逗号分隔的字段
示例表
CREATE TABLE
`foo` (
`id` INT NOT NULL AUTO_INCREMENT ,
`keyword_ids` VARCHAR(128) ,
PRIMARY KEY (`id`)
);
示例数据
INSERT INTO
`foo`
SET
`keyword_ids` = '14,10,5,19,12'
示例查询
SELECT
*
FROM
`foo`
WHERE
(`keyword_ids` LIKE '5,%%'
OR
`keyword_ids` LIKE '%%,5'
OR
`keyword_ids` = '5'
OR
`keyword_ids` LIKE '%%,5,%%')
根据我最近的问题,这工作得很好,但是有什么方法可以改进它?
Sample Table
CREATE TABLE
`foo` (
`id` INT NOT NULL AUTO_INCREMENT ,
`keyword_ids` VARCHAR(128) ,
PRIMARY KEY (`id`)
);
Sample Data
INSERT INTO
`foo`
SET
`keyword_ids` = '14,10,5,19,12'
Sample Query
SELECT
*
FROM
`foo`
WHERE
(`keyword_ids` LIKE '5,%%'
OR
`keyword_ids` LIKE '%%,5'
OR
`keyword_ids` = '5'
OR
`keyword_ids` LIKE '%%,5,%%')
As per my most recent question, this works just fine but is there a way I can improve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
但请注意,此表达式仍然不可控制,这意味着
keyword_ids
上的索引无法改进此查询。如果您希望快速搜索模型,则应该标准化您的模型。
另一种选择是在表中存储逗号分隔的关键字(而不是
ids
),并在它们上创建FULLTEXT
索引:但是,这仅适用于
MyISAM
表。Note, however, that this expression is still not sargable, that means an index on
keyword_ids
cannot improve this query.You should normalize your model if you want this to be searchable fast.
Another option is to store comma-separated keywords (rather than
ids
) in the table and create aFULLTEXT
index on them:This, however, would only work on a
MyISAM
table.看一下 FIND_IN_SET 功能。
Take a look at the FIND_IN_SET function.