如何创建具有特定行为的表

时间:2019-02-15 13:38:22

标签: sql sqlite

基本上我想做的是

  1. 创建具有列(ADDITIONcharacter)的表description
  2. 使用列(THINGidname)创建表addition
  3. 如果THING表中存在加值,则仅允许将项目添加到ADDITION中。
    3.1。非常重要-应该可以附加一个,多个或不附加任何一个值。
  4. 在Python中,我想检查addition表中的THING列,并进行有关列到内容的特定操作。
    4.1。如何实施加法?外键只允许内容与ADDITION表中的字符列完全相同,但是我想允许很多字符。

示例:

  1. create table ADDITION (character char unique not null primary key, description text not null)
  2. create table THING (id integer not null primary key, name text not null, addition text reference ADDITION (character))

在这种情况下,我只能拥有:

添加表内容:

(a,"something"), (b, "something") ...

表格内容:

(1, "apple", "a"), (2, "angle grinder", "b")

但我想拥有

(1, "apple", ""), (2, "angle grinder", "ab"), (3, "cola", "agu")

并且由于外键是不可能的。

还有一件事-是将字符b添加到(3,“ cola”,“ agu”)中的任何SQL方法,还是检查它是否在Python(或Java等)中的唯一方法。代码并附加(如果不存在)?

1 个答案:

答案 0 :(得分:0)

我建议使用更普通的格式,并使用数字而不是字母,然后使用键:

create table addition
(
  add_id integer primary key,
  add_desc text
);

create table thing
(
  th_id integer primary key,
  th_desc text
);

create table thing_addition
(
  th_id integer,
  add_id integer,
  foreign key (th_id) references thing(th_id),
  foreign key (add_id) references addition(add_id)
);

在预期的方法中使用字母会将您限制为一定数量的条目