在PostgreSQL中,ltree数据类型用于处理树形结构数据
CREATE TABLE your_table_name (
id SERIAL PRIMARY KEY,
path ltree
);
INSERT INTO your_table_name (path) VALUES ('1');
INSERT INTO your_table_name (path) VALUES ('1.2');
INSERT INTO your_table_name (path) VALUES ('1.2.3');
INSERT INTO your_table_name (path) VALUES ('1.3');
INSERT INTO your_table_name (path) VALUES ('1.4');
SELECT * FROM your_table_name WHERE path ~ '^1\.2\..*';
SELECT * FROM your_table_name WHERE path ~ '^1\..*';
SELECT * FROM your_table_name WHERE path ~ '^1\.2\.\d+$';
SELECT * FROM your_table_name WHERE path ~ '^1\.\d+\.\d+$';
SELECT * FROM your_table_name WHERE path ~ '^1\.\d+\.\d+$';
SELECT * FROM your_table_name WHERE path ~ '^' || '1.2.3' || '\.\d+$';
SELECT * FROM your_table_name WHERE path ~ '^' || '1.2.3' || '\.\d+$';
注意:在这些示例中,我们使用了~
运算符来匹配路径列中的字符串模式。这是PostgreSQL中LIKE运算符的扩展版本,允许使用正则表达式。