Update statement with joins - postgresql

I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:
question {
id,
name,
groupId,
imageUrl -> i need to update this
}
group {
id,
name,
quizId
}
quiz {
id,
name,
type -> where type is 'History'
}
And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.
UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'

So this is best solution that i came up with, and it worked perfectly for my migration.
UPDATE question SET image_url = 'https://path_to_image.com' WHERE id IN (SELECT q.id FROM question q
JOIN group AS g ON q.groupi_id = g.id
JOIN quiz AS qu ON qu.id = g.quiz_id
WHERE qu.type = 'Lifestyle')
So basically i update image_url to all questions with ID's in sub query, and this is easiest way to do this.

try:
with cte as (
select q.id qid
from question q
join "group" g on g.id = groupId
join quiz z on z.id = quizId
where type = 'History'
)
UPDATE question q
SET image_url = 'pathToImage'
FROM cte.qid = q.id

JOIN three tables on this way:
UPDATE question q
SET image_url = 'pathToImage'
FROM (select g.Id
from group g
JOIN quiz z
ON g.quizID = z.Id
WHERE z.type = 'History') p
ON q.groupId = p.Id;

Related

Ordering data after an intersection Postgresql

I'm working on a db homework question. It asks that the data be in descending order. However, I'm using an intersection in my query because of the many to many relationship.
The schema for Genre is
CREATE TABLE Genre (
movie_id integer REFERENCES Movie(id),
genre GenreType,
primary key (movie_id,genre)
);
My code is currently
$genres = tokenise($argv[1], "&");
$i = 0;
$qry = "
(select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on (m.id = r.movie_id)
join Genre g on (m.id = g.movie_id)
where m.YEAR >= ".$startYear."
and m.YEAR <= ".$endYear."
and g.genre = '".$genres[$i]."')
";
$i++;
while ($i < count($genres)){
$qry = $qry."
intersect
(select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on (m.id = r.movie_id)
join Genre g on (m.id = g.movie_id)
where m.YEAR >= ".$startYear."
and m.YEAR <= ".$endYear."
and g.genre = '".$genres[$i]."')
";
$i++;
}
I'd like to order the final result with the statement
order by r.imdb_score desc, r.num_voted_users desc
However, tagging it onto the end of each select statement doesn't work (the output is still scrambled).
An intersect (or union or except) can only have a single ORDER BY at the end. Even if it "looks like" it belongs to the final query, it applies to the whole result, e.g.:
select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on m.id = r.movie_id
join Genre g on m.id = g.movie_id
where ...
intersect
select m.title, m.YEAR, m.content_rating, m.lang, r.imdb_score, r.num_voted_users
from Movie m
join Rating r on m.id = r.movie_id
join Genre g on m.id = g.movie_id
where ...
order by imdb_score desc, num_voted_users desc
Will sort the complete result of the intersect, note that you can't use a table alias when referencing the columns (and the column names correspond to the name from the first query).
Putting the individual queries between parentheses is not needed.
But the use of intersect seems strange to begin with.
It seems you are simulating a simple IN condition with that. As far as I can tell, you could replace that with a single query that uses where ... and genre in ('genre1', 'genre2', ....)
It will be easier to understand and it will also be a lot faster.
You can still do something like that :
SELECT *
FROM
(
[Your_Entire_Query_With_All_Your_Intersects]
) T
ORDER BY [Your_Conditions];
But I don't know exactly what you want to do. Your query seems quite odd to me. Why the intersect in the first place?

How to add a where clause to an EF query which has a grouping

I'm trying to find the number of bookings each user has made. This code works great - it does a join onto bookings and groups them and then does a count.
var bookingsByUser = from u in _repo.Users()
join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
into g
select new { UserId = u.UserId, TotalBookings = g.Count() };
However, I now want to exclude a certain restaurant, so I try to add a where clause:
var bookingsByUser = from u in _repo.Users()
join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
where b.RestaurantId != 21
into g
select new { UserId = u.UserId, TotalBookings = g.Count() };
However now I get an error "A query body must end with a select clause or a group clause". I can't seem to use "where" on the join table to filter the records before grouping. Is there a better way to do this?
Try this:
var bookingsByUser = from u in _repo.Users()
join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
where b.RestaurantId != 21
group b by u.UserId into sub
select new {
UserId = sub.Key,
TotalBookings = sub.Count()
};

update join and where using Postgres

i have two tables : productprice and product
and i have a field name id on that tables, i would like update field name enddate on productprice base on code on product i try several syntax:
update productprice
set enddate = ’2016-12-31 00:00:00’
from product inner join
productprice
on product.id = productprice.id
where product.code = ‘9301940252’
but the result is "table name “productprice” specified more than once"
What I am doing wrong here? Thanks.
This is the correct syntax for MySQL:
update productprice pp join
product p
on p.id = pp.id
set pp.enddate = '2016-12-31'
where p.code = '9301940252';
Given your error and the fact that the question originally had Postgres and MySQL as a tag, perhaps you want Postgres syntax:
update productprice pp
set enddate = '2016-12-31'
from product p
where p.id = pp.id and p.code = '9301940252';

Entity SQL selecting from more then 3 tables

I am new to Entity framwork and currently trying hard to get used this programming paradigm. I have this query which i want to write in Entity SQL.
SELECT f.id, f.personName, c.Category, j.busCode, s.description, f.StartDate, (SELECT COUNT(*) FROM Analysis WHERE id = f.id) As numOfAnalysis
FROM forms f
INNER JOIN Jobs j ON f.id = j.id
INNER JOIN category c ON j.categoryid = c.categoryid
INNER JOIN stage s ON f.stageid = s.stageid
WHERE j.busCode NOT IN ('xyz', 'YYY')
ORDER BY startDate
I can get records from two tables but as soon as i add third table using the navigation property, i get error table category is not loaded in the current context. I am using .net 3.5. Keep in mind that EDM V2 doest not have foreign keys and i think the only way to traverse through the table relationship is navigation property.
Any help will be deeply appreciated.
Thanks
Coder74
If you use should be able to mount this Linq query.
I tried to put together, but in the rush and no such test is complicated.
You can use this reference as support: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
var result = (from f in forms
join j in Jobs on f.id equals j.id
join c in Category on j.categoryid equals c.categoryid
join s in stage on f.stageid equals s.stageid
join a in Analysis on a.id equals f.id
where !(new int[] { 'xyz', 'YYY' }).Contains(j.busCode)
orderby f.StartDate
select {
id =f.id,
personName = f.personName,
Category = c.Category,
busCode = j.busCode,
description = s.description,
StartDate = f.StartDate,
numOfAnalysis = a.Count()
}).ToList()
Julio Spader
W&S Soluções de Internet

Entity Framework Linq Query of 3 tables

I have this 3 table query that doesn't return any results. Does anybody have any suggestions on what I am doing wrong? _id is a global variable.
'If there is a guest list then display each person in it
Dim guests = (From g In myEntities.GuestLists
From p In myEntities.Pictures
From u In myEntities.UserProfiles
Where g.EventID = _id
Where p.UserID = g.GuestID
Where u.UserID = g.GuestID
Select New With {p.ImUrl, u.FirstName, u.LastName, u.UserID}).SingleOrDefault()
Repeater1.DataSource = guests
Repeater1.DataBind()
This syntax works for a single table or two table query so I assumed 3 tables would be the same.
I think you have to JOIN the tables.
Like this (untested!)
From g In myEntities.GuestLists
Join p In myEntities.Pictures On g.GuestID Equals p.UserID
Join u In myEntities.UserProfiles On g.GuestID Equals u.UserID
Where g.EventID == _id
Select New With {p.ImUrl, u.FirstName, u.LastName, u.UserID}