我有一个包含通知、事件和组织的表格。通知有一个名为event-id的列,该列可以为空。我正在尝试选择通知,对于有事件的通知使用organization.timezone,并且只选择没有时区(或null)的没有事件的通知。下面是一个表格的示例(删除了不相关的字段)
通知表
id | message | event-id
0 | "a" | 0
1 | "b" | nil事件表
id | org-id
0 | 0
1 | 1组织表
id | timezone
0 | "Eastern"
1 | "Other" 我的查询应该返回
id | message | timezone
0 | "a" | "eastern"
1 | "b" | nil我的尝试如下所示(翻译自clojure蜜表,如果有拼写错误,非常抱歉):
Select notifications.id, notifications.message, (case when notifications.event-id then organizations.timezone end)
where (or (= notifications.event-id nil)
(and (= notifications.event-id events.id)
(= events.org-id organizations.id))
end但我得到了
我的查询应该返回
id | message | case
0 | "a" | "eastern"
1 | "b" | nil
1 | "b" | nil我如何修复这个问题,使我不会为每个event-id为空的通知获取重复值?
发布于 2018-11-29 04:18:32
翻译后的SQL是无效的,所以很难说为什么会有重复的结果,但这里有一些有效的SQL,它们将返回您想要的结果,希望您能将其转换为原始格式。
设置
CREATE TABLE notifications (
"id" INTEGER,
"message" VARCHAR(3),
"event-id" INTEGER
);
INSERT INTO notifications
("id", "message", "event-id")
VALUES
('0', 'a', '0'),
('1', 'b', NULL);
CREATE TABLE events (
"id" INTEGER,
"org-id" INTEGER
);
INSERT INTO events
("id", "org-id")
VALUES
('0', '0'),
('1', '1');
CREATE TABLE organizations (
"id" INTEGER,
"timezone" VARCHAR(9)
);
INSERT INTO organizations
("id", "timezone")
VALUES
('0', 'Eastern'),
('1', 'Other');查询
SELECT n.id, n.message, o.timezone
FROM notifications n
LEFT JOIN events e
ON e.id = n."event-id"
LEFT JOIN organizations o
ON o.id = e."org-id";结果
| id | message | timezone |
| --- | ------- | -------- |
| 0 | a | Eastern |
| 1 | b | |https://stackoverflow.com/questions/53524421
复制相似问题