Reputation: 3487
I have the following tables
user
with an id
fielditem
, also with an id fieldpositiverating
with the fields customerid
and itemid
which has an entry if the user gave an implicit positive rating for an item (e.g. has seen/bought/clicked/... it)I want to select the fields user.id
, item.id
and rating
(boolean field)such that for every user and every item rating
is true
iif there exists an entry in the positiverating
table and otherwise false
?
Some thoughts:
SELECT user.id, item.id from user, item
results in the cross
product needed. positiveratings
more or less is such a cross product, but only for rated itemsAssuming that there are 100000 items and the same amount of users, the resulting query needs to be quite efficiently. I suspect some left/right joins are needed, but I feel a bit stuck.
To be more specific, I need a query for PostgreSQL.
Upvotes: 0
Views: 72
Reputation: 1270201
Is this what you are looking for?
select u.userid, i.itemid, (pr.itemid is not null)
from user u cross join
item i left outer join
positiverating pr
on pr.userid = u.userid and pr.itemid = i.itemid;
This assumes no duplicate user/item combinations in the positiverating
table.
If you have duplicates in positiverating
, you could use a group by
. However, I would recommend using exists
instead. I think the following will work:
select u.userid, i.itemid,
exists (select 1 from postivierating where pr.userid = u.userid and pr.itemid = i.itemid)
from user u cross join
item i;
Upvotes: 1