我正在使用nodejs和postgresql。我的postgresql关系有3列:

一堂课可以属于一个或多个标签。
我正在尝试选择属于所请求的标签的所有课程。
例如
我尝试了一些sql查询,比如这个:
const selectLessonByTag = await pgClient.query(
`SELECT DISTINCT ON (lesson_id)
lesson_id FROM "lesson_has_tag"
WHERE tag_id = $1 AND tag_id = $2
GROUP BY lesson_id
ORDER BY lesson_id`,
[2,10]);但这不是预期的答案。
发布于 2022-03-29 13:42:29
您可以这样使用not exists:
select distinct lesson_id
from lesson_tags as lt1
where not exists (
select *
from (values (10), (2)) as required_tags(tag_id)
where not exists (
select *
from lesson_tags as lt2
where lt2.lesson_id = lt1.lesson_id and lt2.tag_id = required_tags.tag_id
)
)很难理解这么少的解释:
required_tags的表值构造函数,它包含值10和2。https://stackoverflow.com/questions/71663062
复制相似问题