【发布时间】:2017-08-05 11:12:34
【问题描述】:
我正在使用 PostgreSQL
我需要什么
在 SELECT 查询中,我需要选择 owner_type(客户端或域)。如果解决方案不存在,请帮助我修改此架构。
架构(表)
- 专辑 - id | client_id (fkey) | domain_id (fkey) |名字
- 客户 - id |名字 |姓氏
- 域 - id |姓名
描述:相册所有者可以是客户端或域或未来的其他节点...
1。创建表查询
CREATE TABLE albums
(
id BIGSERIAL PRIMARY KEY,
client_id BIGINT,
domain_id BIGINT,
name VARCHAR(255) NOT NULL,
FOREIGN KEY (client_id) REFERENCES clients(id),
FOREIGN KEY (domain_id) REFERENCES domains(id),
CHECK ((client_id IS NULL) <> (domain_id IS NULL))
);
2。选择查询
SELECT albums.id,
albums.name,
COALESCE(c.id, d.id) AS owner_id
FROM albums
LEFT JOIN clients c
ON albums.client_id = c.id
LEFT JOIN domains d
ON albums.domain_id = d.id
需要类似 -> if c.id === null -> owner_type = 'Domain'
【问题讨论】:
-
编辑您的问题并提供示例数据和所需结果。
标签: sql postgresql