How to pass a variable to a subselect in a view - sql

I have a table of posts, post_likes, and I need a query that will give me both totals for likes for posts, and also a given specific user's likes for those posts. This means I need a good way of giving MY_USER_ID as input data.
Here's a query that works
create view post_view as
select post.id,
coalesce(sum(post_like.score),0) as score,
(
select score
from post_like
where post.id = post_like.post_id
and post_like.fedi_user_id = MY_USER_ID
) as my_vote,
from post
left join post_like on post.id = post_like.post_id
group by post.id;
BUT my ORM (rust diesel) doesn't allow me to set or query for that necessary MY_USER_ID field, since it's a subquery.
I'd really love to be able to do something like:
select *
from post_view
where my_user_id = 'X';

Expose my_user_id on select clause of view
-- get all of the user's score on all post, regardless of the user liking the post or not
create view post_view as
select
u.id as my_user_id,
p.id as post_id,
sum(pl.score) over (partition by p.id) as score,
coalesce(pl.score, 0) as my_vote -- each u.id's vote
from user u
cross join post p
left join post_like pl on u.id = pl.fedi_user_id and p.id = pl.post_id;
select * from post_view where my_user_id = 'X';
UPDATE
This can obtain post's scores even when no user is given
create view post_view as
with all_post as
(
select
p.id as post_id,
sum(pl.score) as score
from post p
left join post_like pl on p.id = pl.post_id
group by p.id
)
select
u.id as my_user_id,
ap.post_id,
ap.score,
coalesce(pl.score, 0) as my_vote
from user u
cross join all_post ap
left join post_like pl on u.id = pl.fedi_user_id and ap.post_id = pl.post_id
union all
select
'' as my_user_id,
ap.post_id,
ap.score,
0 as my_vote
from all_post ap
;
select * from post_view where my_user_id = 'X';
When no user is passed, select the query denoted by my_user_id of ''
select * from post_view where my_user_id = '';

you can move that condition in on clause
create view post_view as
select post.id,
coalesce(sum(post_like.score),0) as score
from post
left join post_like
on post.id = post_like.post_id and post_like.fedi_user_id = MY_USER_ID
group by post.id;

You can move the logic to the select using conditional aggregation:
select p.id,
coalesce(sum(pl.score), 0) as score,
sum( (pl.fedi_user_id = MY_USER_ID)::int ) as my_vote
from post p left join
post_like pl
on p.id = pl.post_id
group by p.id;

Related

converting subquery to join in postgresql

select p.postid postid,p.posttypeid posttypeid,
(select count(parentid) as no_of_answers from post
where parentid=p.postid), p.title title,
p.body body ,
p.creationdate creationdate,
p.modifieddate modifieddate,
p.modifieduserid modifieduserid,
p.score score,p.views no_of_views,
u.userid userid
from post
as p
left outer join user_quest as u on p.owneruserid = u.userid
where p.posttypeid = 1
Order by p.creationdate desc
LIMIT 10 OFFSET 0;
I need to convert his subquery to join, please help
You could use CTE:
WITH counts AS (
SELECT
count(parentid) AS no_of_answers,
parentid
FROM post
GROUP BY parentid
)
SELECT
p.postid,
p.posttypeid,
p.title,
COALESCE(c.no_of_answers, 0) AS no_of_answers,
p.body,
p.creationdate,
p.modifieddate,
p.modifieduserid,
p.score,
p.views AS no_of_views,
u.userid
FROM post AS p
LEFT JOIN counts c ON (c.parentid = p.postid)
LEFT JOIN user_quest AS u ON (p.owneruserid = u.userid)
WHERE p.posttypeid = 1
ORDER BY p.creationdate DESC
LIMIT 10 OFFSET 0;
or put yours subquery to JOIN:
SELECT
p.postid,
p.posttypeid,
p.title,
COALESCE(c.no_of_answers, 0) AS no_of_answers,
p.body,
p.creationdate,
p.modifieddate,
p.modifieduserid,
p.score,
p.views AS no_of_views,
u.userid
FROM post AS p
LEFT JOIN
(
SELECT
count(parentid) AS no_of_answers,
parentid
FROM post
GROUP BY parentid
) c ON (c.parentid = p.postid)
LEFT JOIN user_quest AS u ON (p.owneruserid = u.userid)
WHERE p.posttypeid = 1
ORDER BY p.creationdate DESC
LIMIT 10 OFFSET 0;
But I would prefer CTE. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. And it's look pretties because is easier to read, at least i thing so.

Limitting results in association

I want to limit the results in a lateral join, so that it only returns the N most recent matches.
This is my query, but the limit inside the join does not seem to work, as it returns all visitors
select am.id, am.title, ame.event, array_agg(row_to_json(visitors))
from auto_messages am
left join apps a on am.app_id = a.id
left join app_users au on a.id = au.app_id
left join auto_message_events ame on ame.auto_message_id = am.id
left join lateral (
select
id,
name,
avatar,
ame.inserted_at
from visitors v
where v.id = ame.visitor_id
order by ame.inserted_at desc
limit 1
) as visitors on visitors.id = ame.visitor_id
where am.id = '100'
group by am.id, ame.event
I am pretty sure the problem is with ame. That is where the rows are generated. The join to visitors is only picking up additional information.
So, this might solve your problem:
select am.id, am.title, visitors.event, array_agg(row_to_json(visitors))
from auto_messages am left join
apps a
on am.app_id = a.id left join
app_users au
on a.id = au.app_id left join lateral
(select v.id, v.name, v.avatar,
ame.event, ame.inserted_at, ame.auto_message_id
from auto_message_events ame join
visitors v
on v.id = ame.visitor_id
order by ame.inserted_at desc
limit 1
) visitors
on visitors.auto_message_id = am.id
where am.id = '100'
group by am.id, visitors.event;
You also might want to change your select clause, if you only want a subset of columns.

Take additional field value

I have this query:
Select
p.Id, p.Nazwa
From
tbProjekt p
Where
EXISTS (select UP.*
from tbUserProject UP
where UP.ProjectId = p.Id And UP.UserId = 1)
I want to select the additional column UP.IsFullAccessso so change the first line to this one:
Select
p.Id, p.Nazwa, UP.IsFullAccess
but I get an error:
The multi-part identifier "UP.IsFullAccess" could not be bound.
You need to join to tbUserProject in your main query then:
Select p.Id, p.Nazwa, UP.IsFullAccess
From tbProjekt p
INNER JOIN tbUserProject UP
ON p.Id = UP.ProjectId
WHERE UP.UserId = 1
UP exists only within the EXISTS sub-query and can't be accessed from the main query. You may be able to use a JOIN instead:
SELECT
p.Id,
p.Nazwa,
UP.IsFullAccess
FROM tbProjekt p
JOIN tbUserProject UP
ON UP.ProjectId = p.Id
AND UP.UserId = 1
The main difference is the possibility of duplicates if you have more than one matching record in the tbUserProject table.
If you need unique values from tbProject and there is many values in tbUserProject for one project and one user use this:
SELECT
p.Id,
p.Nazwa,
UP.IsFullAccess
FROM tbProjekt p
INNER JOIN
(
select ProjectId, MAX(IsFullAccess) as IsFullAccess from tbUserProject UP where UP.UserId = 1
group by ProjectId
) UP ON UP.ProjectId = p.Id

SQL SELECT statement with users, roles and rights

Lets say that I have tables:
Users
Users_in_Roles
Roles
Rights_in_Roles
Rights
Keys are standard( UserFk, RoleFk, RightFk)
The question is: how to get all users that are in role with right X (id = 100)
I Have no idea how to touch this problem. Please help and sorry for my english.
SELECT [dbo].[System_Users].[Id]
,[UserName]
,[FirstName]
,[LastName]
,[Email]
,RoleFk
,[dbo].[System_Roles].Name
FROM [dbo].[System_Users]
INNER JOIN [dbo].[System_Roles_System_Users]
ON [dbo].[System_Roles_System_Users].UserFk = [dbo].[System_Users].Id
INNER JOIN [dbo].[System_Roles]
ON [dbo].[System_Roles].Id = [dbo].[System_Roles_System_Users].RoleFk
WHERE ?
I tryied sth like that, could you tell me what iw wrong?
SELECT
DISTINCT System_Users.Id,
System_Users.FullName
FROM System_Users
INNER JOIN Dict_Rights_System_Users
ON System_Users.Id = Dict_Rights_System_Users.UserFk
INNER JOIN System_Roles_System_Users
ON System_Roles_System_Users.UserFk = System_Users.Id
WHERE
RightFk = 136
OR
136 IN (SELECT Dict_Rights_System_Roles.RightFk FROM Dict_Rights_System_Roles WHERE
Dict_Rights_System_Roles.RoleFk = System_Roles_System_Users.RoleFk)
ORDER BY System_Users.FullName ASC
You will need to JOIN the tables on the key relationships. The basic structure will be:
select u.Id,
u.UserName,
u.FirstName,
u.LastName,
u.Email,
r.RoleFk,
r.Name RoleName,
rt.Name RightName
from users u
inner join users_in_roles ur
on u.id = ur.userfk
inner join roles r
on ur.rolefk = r.id
inner join rights_in_roles rr
on r.rolefk = rr.rolefk
inner join rights rt
on rr.rightfk = rt.id
where rt.id = 100
If you need help learning JOIN syntax here is a great reference:
A Visual Explanation of SQL Joins
You can try with this:
SELECT *
FROM Users u
WHERE EXISTS (
SELECT ur.RoleFk
FROM Users_in_Roles ur
WHERE u.UserPk = ur.UserFk
AND EXISTS
(
SELECT 1
FROM Rights_in_Roles rr
WHERE rr.RoleFk = ur.RoleFk
AND rr.RightFk = 100
)
)
OR EXISTS (
SELECT 1
FROM Users_Rights uri
WHERE u.UserPk = uri.UserFk
AND uri.RightFk = 100
)
Note that the above query doesn't return RoleFk and Name for the role.
Another approach would be:
SELECT u.Id
,u.UserName
,u.FirstName
,u.LastName
,u.Email
,rr.RoleFk
,r.Name
FROM Users u
-- get users that are in role that has right
LEFT JOIN
Users_in_Roles ur ON
ur.UserFk = u.UserPk
LEFT JOIN
Rights_in_Roles rr ON
rr.RoleFk = ur.RoleFk
AND rr.RightFk = 100
LEFT JOIN
Rights r ON
r.RolePk = rr.RoleFk
-- get users that have a right granted to them directly
LEFT JOIN
Users_Rights uri ON
u.UserPk = uri.UserFk
AND uri.RightFk = 100
WHERE rr.RoleFk IS NOT NULL OR uri.UserFk IS NOT NULL

SQL SELECT with m:n relationship

I have m:n relationship between users and tags. One user can have m tags, and one tag can belong to n users. Tables look something like this:
USER:
ID
USER_NAME
USER_HAS_TAG:
USER_ID
TAG_ID
TAG:
ID
TAG_NAME
Let's say that I need to select all users, who have tags "apple", "orange" AND "banana". What would be the most effective way to accomplish this using SQL (MySQL DB)?
SELECT u.*
FROM (
SELECT user_id
FROM tag t
JOIN user_has_tag uht
ON uht.tag_id = t.id
WHERE tag_name IN ('apple', 'orange', 'banana')
GROUP BY
user_id
HAVING COUNT(*) = 3
) q
JOIN user u
ON u.id = q.user_id
By removing HAVING COUNT(*), you get OR instead of AND (though it will not be the most efficient way)
By replacing 3 with 2, you get users that have exactly two of three tags defined.
By replacing = 3 with >= 2, you get users that have at least two of three tags defined.
In addition to the other good answers, it's also possible to check the condition in a WHERE clause:
select *
from user u
where 3 = (
select count(distinct t.id)
from user_has_tag uht
inner join tag t on t.id = uht.tag_id
where t.name in ('apple', 'orange', 'banana')
and uht.user_id = u.userid
)
The count(distinct ...) makes sure a tag is counted only once, even if the user has multiple 'banana' tags.
By the way, the site fruitoverflow.com is not yet registered :)
You can do it all with joins...
select u.*
from user u
inner join user_has_tag ut1 on u.id = ut1.user_id
inner join tag t1 on ut1.tag_id = t1.id and t1.tag_name = 'apple'
inner join user_has_tag ut2 on u.id = ut2.user_id
inner join tag t2 on ut2.tag_id = t2.id and t2.tag_name = 'orange'
inner join user_has_tag ut3 on u.id = ut3.user_id
inner join tag t3 on ut3.tag_id = t3.id and t3.tag_name = 'banana'
SELECT *
FROM USER u
INNER JOIN USER_HAS_TAG uht
ON u.id = uht.user_id
INNER JOIN TAG t
ON uht.TAG_ID = t.ID
WHERE t.TAG_NAME IN ('apple','orange','banana')