包含数组的列的复杂SELECT

时间:2017-11-12 23:23:23

标签: sql postgresql

我正在尝试使用2个表在PostgreSQL数据库中执行查询:

  1. channel
  2. videos
  3. 我想让所有用户和每个用户拥有最多视图数量的1个视频。我需要按以下标准查找用户:

    • nameid
    • 相似的任何用户
    • title类似于id
    • 的所有用户

    我设法使用以下代码:

       SELECT ch.*,
       yv.id as video_id,
       yv.title as video_title,
       yv.view_count as video_view_count,
       yv.tags as video_tags,
       FROM channel as ch
       LEFT JOIN
           (SELECT channel_id, MAX(id) as video_id
           FROM videos
           GROUP BY channel_id
           ) as vo 
           ON ch.id = vo.channel_id
           INNER JOIN videos as yv
           ON vo.video_id = yv.id
           AND (
               ch.name ILIKE '%${id}%'
               OR yv.title ILIKE '%${id}%'
               )
           ORDER BY view_count DESC
           LIMIT ${req.params.count}
    

    tags表中有一个videos列,它有一个标记数组(字符串)。我想添加新条件 - tags中标记类似id的所有视频。 我尝试在下面添加代码,但它不起作用:

             AND (
               ch.name ILIKE '%${id}%'
               OR yv.title ILIKE '%${id}%'
               OR '%${id}%' = ANY(yv.tags)'
               )
    

    据我所知 - 联合表只有1个视频,这就是为什么它不起作用。 它可以通过以下方式完成:

       SELECT ch.*,
       yv.id as video_id,
       yv.title as video_title,
       yv.view_count as video_view_count,
       yv.tags as video_tags,
       FROM channel as ch
       LEFT JOIN
           (SELECT channel_id, MAX(id) as video_id
           FROM videos
           GROUP BY channel_id
       WHERE '%${id}%' = ANY(tags)
           ) as vo 
           ON ch.id = vo.channel_id
           INNER JOIN videos as yv
           ON vo.video_id = yv.id
           AND (
               ch.name ILIKE '%${id}%'
               OR yv.title ILIKE '%${id}%'
               )
           ORDER BY view_count DESC
           LIMIT ${req.params.count}
    

    它不起作用,因为:

       WHERE '%${id}%' = ANY(tags)
    

       AND (
           ch.name ILIKE '%${id}%'
           OR yv.title ILIKE '%${id}%')
    

    无关。

    我怎么能这样做?

      '%${id}%' ILIKE ANY(tags)
    

    有办法吗?

0 个答案:

没有答案