Ответы пользователя по тегу PostgreSQL
  • Как правильно составить запрос к базе?

    @x_shader
    Oracle & Coffee
    Раз тег не ORM, то можете погонять на своих тестовых данных SQL.
    Подставьте ваш $date вместо timestamp '2019-06-27 11:15:00'

    /*
    with channel_program as (
      select 1 as channel_id, 1 as program_id, timestamp '2019-06-27 09:00:00' as start_time, timestamp '2019-06-27 10:00:00' as end_time union all
      select 1 as channel_id, 2 as program_id, timestamp '2019-06-27 10:02:00' as start_time, timestamp '2019-06-27 11:00:00' as end_time union all
      select 1 as channel_id, 3 as program_id, timestamp '2019-06-27 11:10:00' as start_time, timestamp '2019-06-27 11:30:00' as end_time union all
      select 1 as channel_id, 4 as program_id, timestamp '2019-06-27 11:35:00' as start_time, timestamp '2019-06-27 12:00:00' as end_time union all
      select 1 as channel_id, 4 as program_id, timestamp '2019-06-27 12:00:00' as start_time, timestamp '2019-06-27 12:30:00' as end_time
    )
    */
    
    select t.program_id
      from (
            select 
                   program_id
                  ,lag(start_time) over (order by start_time) lag_start_time
                  ,lead(end_time) over (order by start_time) lead_end_time
              from channel_program
           ) t
     where timestamp '2019-06-27 11:15:00' between coalesce(t.lag_start_time, timestamp '1991-01-01 00:00:00') 
                                               and coalesce(t.lead_end_time, timestamp '2999-01-01 00:00:00')
    Ответ написан
    Комментировать
  • Как ускорить запрос с DISTINCT в PostgreSQL?

    @x_shader
    Oracle & Coffee
    Должно помочь избавление от конкатенации.

    SELECT DISTINCT CITY, AREA, REGION FROM youtube
    или
    SELECT CITY,  AREA, REGION
    FROM youtube
    GROUP BY CITY,  AREA, REGION


    Если сильно нужно получать именно конкатенированный результат, то подзапрос все-равно будет быстрее
    SELECT  "CITY" || ' | '  || "AREA" || ' | ' || "REGION" FROM (
        SELECT CITY,  AREA, REGION
        FROM youtube
        GROUP BY CITY,  AREA, REGION) t
    Ответ написан
    9 комментариев