我正在尝试使用2个表在PostgreSQL数据库中执行查询:
channel
videos
我想让所有用户和每个用户拥有最多视图数量的1个视频。我需要按以下标准查找用户:
name
与id
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)
有办法吗?