@winmasta

Как правильно составить запрос postgresql?

select @rec_id="recordId" from catalog_49_links where "catalogId" = 36 and "catalogRecordId" = 352 order by "createdAt" desc limit 1;
select @new_rec_id="recordId" from catalog_49_links where "recordId"=@rec_id and "catalogId" = 56 or ("catalogId" = 36 and "catalogRecordId" = 352) order by "createdAt" desc limit 1;


В mssql studio такой код работает а в pgAdmin нет.
Суть запроса: получить значение поля recordId согласно условиям первого запроса и затем получить значение этого же поля, но согласно условиям второго запроса, где участвует значение из первого запроса.
  • Вопрос задан
  • 364 просмотра
Решения вопроса 1
zoroda
@zoroda
Необычный Fullstack
В MS SQL принято писать в процедурном стиле, в том числе используя переменные.
Вы можете использовать процедурные расширения PostgreSQL, как отметил выше Сергей Горностаев, в функциях.
У pgAdminIII есть своё процедурное расширение pgScript. Обратите внимание на то, что скрипты на pgScript будут работать только из-под pgAdminIII.

На чистом SQL, без использования переменных, ваш запрос будет выглядеть примерно так:

with rec as (
select "recordId" as rec_id 
from catalog_49_links
 where "catalogId" = 36 and "catalogRecordId" = 352 
order by "createdAt" desc 
limit 1
)
select "recordId" as new_rec_id from catalog_49_links where "recordId" in (select rec_id from rec) and "catalogId" = 56 or ("catalogId" = 36 and "catalogRecordId" = 352) order by "createdAt" desc limit 1;

или
with rec as (
select "recordId" as rec_id 
from catalog_49_links
 where "catalogId" = 36 and "catalogRecordId" = 352 
order by "createdAt" desc 
limit 1
)
select "recordId" as new_rec_id 
from catalog_49_links
join rec on rec.rec_id = catalog_49_links."recordId"
where "catalogId" = 56 or ("catalogId" = 36 and "catalogRecordId" = 352) 
order by "createdAt" desc limit 1;
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
sergey-gornostaev
@sergey-gornostaev Куратор тега PostgreSQL
Седой и строгий
В самом PostgreSQL переменные можно объявлять только в хранимых процедурах. Но в pgAdmin есть pgScript, который вам и нужен, похоже:
declare @new_rec_id;

set @new_rec_id = select recordId from catalog_49_links
where recordId in (
  select recordId from catalog_49_links
  where catalogId = 36 and catalogRecordId = 352
  order by createdAt desc
  limit 1
)
and catalogId = 56 or (catalogId = 36 and catalogRecordId = 352)
order by createdAt desc
limit 1;
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы