假设我有一个包含字段A
和的表B
。我在A
+上进行常规查询B
,所以我在 上创建了一个复合索引(A,B)
。A
复合索引是否也会对查询进行全面优化?
此外,我在 上创建了一个索引A
,但 Postgres 仍然只使用复合索引来查询A
。如果前面的答案是肯定的,我想这并不重要,但是为什么它默认选择复合索引,如果单个A
索引可用?
我有几个关于在 PostgreSQL 中使用索引的问题。我有一个Friends
带有以下索引的表:
Friends ( user_id1 ,user_id2)
Run Code Online (Sandbox Code Playgroud)
user_id1
并且user_id2
是user
表的外键
这些是等价的吗?如果不是,那为什么?
Index(user_id1,user_id2) and Index(user_id2,user_id1)
Run Code Online (Sandbox Code Playgroud)如果我创建主键(user_id1,user_id2),它会自动为它创建索引吗?
如果第一个问题中的索引不相等,那么在上面的主键命令上创建了哪个索引?
假设我们有用户,每个用户可以有多个电子邮件地址
CREATE TABLE emails (
user_id integer,
email_address text,
is_active boolean
)
Run Code Online (Sandbox Code Playgroud)
一些示例行
user_id | email_address | is_active
1 | foo@bar.com | t
1 | baz@bar.com | f
1 | bar@foo.com | f
2 | ccc@ddd.com | t
Run Code Online (Sandbox Code Playgroud)
我想强制执行一个约束,即每个用户都只有一个活动地址。我怎样才能在 Postgres 中做到这一点?我可以这样做:
CREATE UNIQUE INDEX "user_email" ON emails(user_id) WHERE is_active=true;
Run Code Online (Sandbox Code Playgroud)
这可以防止用户拥有多个活动地址,但我相信不会防止他们的所有地址都设置为 false。
如果可能的话,我更愿意避免使用触发器或 pl/pgsql 脚本,因为我们目前没有这些脚本,而且设置起来会很困难。但我很感激知道“唯一的方法是使用触发器或 pl/pgsql”,如果是这样的话。
postgresql database-design constraint referential-integrity ddl
我有一个没有被另一个实体定义就不能存在的实体,我希望这个实体参与多对多关系。
例子:一个艺人有一张专辑(没有艺人就不能存在专辑),专辑也有很多曲目,但同一曲目可以存在于多个专辑中。
所以我们在专辑和曲目之间有一个多对多的关系。
如果专辑是弱实体,则其主键是引用艺术家的外键,因此它不能是表示多对多关系的另一个表的外键。
问题是:SQL中是否可以有这种关系,如果可以,我该如何表达?
我目前在两个实体之间有一个外键,我想让这种关系以其中一个表的 entityType 为条件。这是表的层次结构,这是通过从子级到父级的FK 引用完成的
Store
/ \
Employees \
TransactionalStores
/ | \
Kiosks | BrickMortars
Onlines
Run Code Online (Sandbox Code Playgroud)
我目前有从员工到商店的 FK 关系
ALTER TABLE Employees ADD CONSTRAINT Employee_Store
FOREIGN KEY (TransStoreId)
REFERENCES TransactionalStores(StoreId)
Run Code Online (Sandbox Code Playgroud)
我想添加条件:
WHERE TransactionalStores.storeType != 'ONLINE_TYPE'
Run Code Online (Sandbox Code Playgroud)
这是可能的还是我必须将 TransactionalStores 子类化为两个新的子类型(例如 PhysicalStores 和 VirtualStores)
我有3张桌子:
当我设计 ER 模型时,它具有循环依赖关系:
1:N 人 --------< 帖子 1:N 发帖 ----------< 点赞 1:N 人们 --------< 喜欢
逻辑是:
1个人可以有很多帖子。
1个帖子有很多赞。
1个人可以点赞多个帖子(创建的人不能点赞自己的帖子)。
我怎样才能消除这种循环设计?还是我的数据库设计错了?
我正在尝试对电路板上零件的放置进行建模。没有任何有意义的限制,我的基本架构如下所示:
create table part (
part_id bigserial primary key,
name text not null,
width double precision not null,
height double precision not null
);
create table board (
board_id bigserial primary key,
width double precision not null,
height double precision not null
);
create table board_part (
board_id bigint not null references board,
part_id bigint not null references part,
position point not null
);
Run Code Online (Sandbox Code Playgroud)
对于b
和b2
any board_part
s,我想强制执行以下约束:
b
位于黑板上:
box(b.position, …
Run Code Online (Sandbox Code Playgroud)postgresql database-design referential-integrity spatial exclusion-constraint
postgresql ×6
constraint ×2
foreign-key ×2
index ×2
ddl ×1
index-tuning ×1
mysql ×1
performance ×1
primary-key ×1
spatial ×1