【笔记】MySQL直接存储ids

前言

MySQL直接存储以逗号分隔的ids,作为多表关联的外键列表

定义表结构

1
2
3
4
5
6
7
8
CREATE TABLE `table` (
id BIGINT,
other_ids TEXT
)

CREATE TABLE `other` (
id BIGINT
)

存储ids

1
INSERT INTO `table` VALUES (1, "1,2,3");

从ids查找是否存在指定id

  • FIND_IN_SET()返回查找到的索引位置,如果返回0则表示没有找到
1
SELECT * FROM `table` WHERE FIND_IN_SET("1", `other_ids`) > 0;

不重复向ids末尾追加id

1
UPDATE `table` SET `other_ids` = CONCAT(`other_ids`, ",", "4") WHERE FIND_IN_SET("4", `other_ids`) = 0;

完成