另一个用户的 Postgresql 现有喜欢

标签 postgresql

我有三个表: 用户, 项目。 喜欢。

CREATE TABLE t_users (
user_id varchar PRIMARY KEY,
name varchar
);

CREATE TABLE t_items (
item_id varchar PRIMARY KEY,
owner_id varchar
);

CREATE TABLE t_likes (
like_id varchar PRIMARY KEY,
item_id varchar references t_items(item_id),
user_id varchar references t_users(user_id)
);

INSERT INTO t_users VALUES ('us123', 'us123');
INSERT INTO t_users VALUES ('us456', 'us456');
INSERT INTO t_users VALUES ('us789', 'us789');

INSERT INTO t_items VALUES ('it123', 'us123');
INSERT INTO t_items VALUES ('it456', 'us123');
INSERT INTO t_items VALUES ('it789', 'us123');
INSERT INTO t_items VALUES ('it987', 'us456');
INSERT INTO t_items VALUES ('it654', 'us456');
INSERT INTO t_items VALUES ('it321', 'us456');

INSERT INTO t_likes VALUES ('lk123', 'it123', 'us789');
INSERT INTO t_likes VALUES ('lk456', 'it456', 'us123');
INSERT INTO t_likes VALUES ('lk789', 'it789', 'us789');
INSERT INTO t_likes VALUES ('lk987', 'it987', 'us456');
INSERT INTO t_likes VALUES ('lk654', 'it654', 'us789');
INSERT INTO t_likes VALUES ('lk321', 'it321', 'us789');

select * from t_items where owner_id = 'us123';

如何发出一个请求,该请求将给出属于用户项目,同时考虑到现有喜欢另一个用户 'us789' ?

Worked example

我需要结果:

   item_id  owner_id  its_like
1   it123   us123   us789
2   it456   us123
3   it789   us123   us789

谢谢。

最佳答案

使用左连接。将其他用户标识放在连接条件中:

select i.item_id, i.owner_id, l.user_id as its_like
from t_items i
left join t_likes l
on i.item_id = l.item_id and l.user_id = 'us789'
where owner_id = 'us123';

 item_id | owner_id | its_like 
---------+----------+----------
 it123   | us123    | us789
 it456   | us123    | 
 it789   | us123    | us789
(3 rows)

关于另一个用户的 Postgresql 现有喜欢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51449709/

相关文章:

java - 如何在 native spring-data @Query 中使用命名参数?

sql - 按合适的时间加入表

postgresql - 使用 order_by 和分页的 Flask-SqlAlchemy 查询非常慢

python - 在 python 中使用带有条件的服务器端游标读取大量数据

postgresql - 在电话字段的前 3 个字符(区号)上创建索引?

java - 带有 Postgres 的 Payara/EclipseLink 中 ScrollableCursor 的内存问题

postgresql - Postgres 根据查询结果从表中选择

java - 我如何为 postgreSQL 创建服务器端应用程序(适用于 Android 应用程序,没有 Firebase)

python - 来自 ManyToManyField 的 Django 最大相似度(TrigramSimilarity)

c++ - PostgreSQL C API (libpq) 是否允许您使用结果而不是存储结果?