GBase 8s SET集合类型简介

GBase 8s SET集合类型简介

在GBase 8s V8.8中,集合数据类型为处理多值属性提供了灵活的解决方案。本文将介绍SET类型的特性、使用方法,并对比LIST、MULTISET两种同类集合类型,帮助开发者根据业务场景选择合适的数据结构。

什么是SET


SET是GBase 8s的一种集合数据类型,具有以下核心特征:

无序:元素没有固定的存储顺序
唯一:每个元素值不可重复,自动去重


常见set的使用方法


数据准备:新建包含set类型的表:
(集合元素不能具有 NULL 值。必须对集合元素指定 NOT NULL约束,且没有任何其他约束有效)

drop database if exists testdb; create database testdb with log; database testdb; create table student ( id int, name varchar(10), course set(varchar(20) not null)); insert into student values( 1, 'xiaohong', set{'c','c++'}); insert into student values( 2, 'xiaoming', set{'js'});



当使用 dbaccess来更新集合类型时,必须更新整个集合。无法在原先set集合中添加新元素或者删除某个元素。以下用法不适用

update student set course = course|| 'python' where id =1; update student set course = course + 'python' where id =1; update student set course = course + {'python'} where id =1; update student set course = course + set{'python'} where id =1;


删除set集合中包含目标元素的记录

delete from student where 'js' in course;


整体修改set集合

update student set course = set{'java'} where id =1;


1.查询set集合中所有元素

select * from table((select course from student where id =1)) as t1(course);

2.查询目标元素是否在set集合中(使用带有 IN 关键字的WHERE 子句来查询目标元素是否在set集合中)

select * from student where 'java' in course;

扩充list、multiset与set


1、list、multiset与set区别
  • set是无序元素集合,每个元素值唯一。
  • MULTISET 是无序元素集合,每个元素值可重复。
  • LIST 是有序元素集合,每个元素值可重复。
  • 注:set、Multiset和list都必须指定not null约束,且没有任何其他约束有效
2、示例


1)创建list、Multiset、set相关的表

create table student1 ( id int, name varchar(10), english set(varchar(20) not null), chinese list(varchar(20) not null), math multiset(varchar(20) not null));

2)集合中插入不同的数据

insert into student1 values( 1, 'lihua', set{'89','88'}, list{'89','88'}, multiset{'89','88'}); select * from student1; id 1 name lihua english SET{'89','88'} chinese LIST{'89','88'} math MULTISET{'89','88'} 1 row(s) retrieved.

3)集合中插入相同的数据

insert into student1 values( 1, 'lihua', set{'88','88'}, list{'88','88'}, multiset{'88','88'}); select * from student1; id 1 name lihua english SET{'88'} chinese LIST{'88','88'} math MULTISET{'88','88'} 1 row(s) retrieved.

插入相同元素时:set不支持重复元素,可以插入成功,但是set会自动去重