SQL 如何 SELECT 基于多行条件的 id
SQL how to SELECT an id based on multiple rows conditions
我正在使用 nodejs 和 postgresql。我的 postgresql 关系有 3 列:
- id
- lesson_id
- tag_id.
一节课可以属于 1 个或多个标签。
我正在尝试 select 所有属于所请求标签的课程。
例如
- 请求的标签是 id 10 和 2,查询应以课程 id = 3 响应
- 请求的标签是 id 1 和 17,查询应以课程 id = 6 响应
- 请求的标签是 3,查询应以课程 ID 1、2、4 响应
我已经尝试了一些 sql 类似这样的查询:
const selectLessonByTag = await pgClient.query(
`SELECT DISTINCT ON (lesson_id)
lesson_id FROM "lesson_has_tag"
WHERE tag_id = AND tag_id =
GROUP BY lesson_id
ORDER BY lesson_id`,
[2,10]);
但这不是预期的答案。
您可以像这样使用 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
的 table 值构造函数包含值 10 和 2
- 内部查询测试外部查询的一课是否不存在 10 或 2
- 如果内部查询没有产生匹配的外部行选择
我正在使用 nodejs 和 postgresql。我的 postgresql 关系有 3 列:
- id
- lesson_id
- tag_id.
一节课可以属于 1 个或多个标签。
我正在尝试 select 所有属于所请求标签的课程。
例如
- 请求的标签是 id 10 和 2,查询应以课程 id = 3 响应
- 请求的标签是 id 1 和 17,查询应以课程 id = 6 响应
- 请求的标签是 3,查询应以课程 ID 1、2、4 响应
我已经尝试了一些 sql 类似这样的查询:
const selectLessonByTag = await pgClient.query(
`SELECT DISTINCT ON (lesson_id)
lesson_id FROM "lesson_has_tag"
WHERE tag_id = AND tag_id =
GROUP BY lesson_id
ORDER BY lesson_id`,
[2,10]);
但这不是预期的答案。
您可以像这样使用 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
的 table 值构造函数包含值 10 和 2 - 内部查询测试外部查询的一课是否不存在 10 或 2
- 如果内部查询没有产生匹配的外部行选择