sql - Postgresql左连接问题
问题描述
我有两张桌子
create table sources (
user_id bigint,
source varchar,
created timestamp default now(),
unique(user_id, source)
)
create table subscriptions (
user_id bigint unique primary key,
plan int not null references plans(id),
starts timestamp default now(),
ends timestamp default now() + interval '30' day
)
当用户有活动订阅时,我尝试从源中选择所有内容,我使用此查询
SELECT src.* FROM sources AS src LEFT JOIN subscriptions as sub ON sub.user_id=src.user_id WHERE now() < sub.ends
但是,它并没有返回所有数据,当我尝试时问题变得清晰
SELECT * FROM sources AS src LEFT JOIN subscriptions as sub ON sub.user_id=src.user_id
解决方案
更新
你left join
的工作。如果您的图像是,SELECT * FROM sources AS src LEFT JOIN subscriptions as sub ON sub.user_id=src.user_id
那么您的一些用户没有订阅。
SELECT * FROM sources AS src LEFT JOIN subscriptions ...
only 确保sources
将获取 in 中的每个匹配行,而不管它是否在subscriptions
.
[当我认为这是一个不同的问题时,我写了其余的,但建议仍然存在。]
这是可能的,因为sources.user_id
没有设置为外键,因此数据库无法强制引用完整性。就数据库而言,sources.user_id
只是一些数字。如果您删除一个用户,他们的来源和订阅将一直存在。
一般来说...
- 聪明的主键只会带来复杂性。给出比简单连接表更复杂的所有内容
id bigserial primary key
并完成它。 - 声明一切
not null
,除非你有充分的理由它应该为空。 - 用于
on delete cascade
在删除用户时进行清理,但请参见下文。
create table sources (
id bigserial primary key,
-- When a user is deleted, its sources will also be deleted
user_id bigint not null references users(id) on delete cascade,
source varchar not null,
created timestamp not null default now(),
unique(user_id, source)
)
create table subscriptions (
id bigserial primary key,
-- When a user is deleted, its subscriptions will also be deleted
user_id bigint not null unique references foreign key users(id) on delete cascade,
-- Make foreign key names consistent, and use a consistent type for ids.
plan_id bigint not null references plans(id) on delete cascade,
starts timestamp not null default now(),
ends timestamp not null default now() + interval '30' day
)
当已删除的用户仍有来源和订阅时是否使用on delete cascade
取决于您要如何处理这种情况。您可能希望阻止删除仍然具有活动源和子的用户,在这种情况下,请停止on delete cascade
并手动清理用户的源和子。
推荐阅读
- python - 有没有办法测试输入是否是pygame中的图像?
- python - Django:有没有办法将管理员中的表单复制到面向用户的页面?
- php - PHP session_name():会话处于活动状态时无法更改会话名称错误
- pandas - Pandas 合并两个 df,其中 df1.column 为 = 或介于 df2.column1 和 df2.column2 之间
- c# - 在将连接字符串作为查询字符串传递后,SqlDataAdapter 查询不起作用,这是怎么回事?
- python - matplotlib 中使用 Flask 的变音符号
- apache-spark - 如何将火花数据帧的结果存储到scala val
- sql - 在 db2 SQL 中选择日期范围
- git - 我不太明白git中环境变量的概念
- java - 从 java 调用 Google Cloud Run