SQL如何根据多行条件选择一个id
我正在与Nodejs和PostgreSQL合作。我的PostgreSQL关系有3列:
- ID
- thress_id
- tag_id。
一课可以属于1或多个标签。
我正在尝试选择属于请求标签的所有课程。
例如,
- 请求的标签是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 = $1 AND tag_id = $2
GROUP BY lesson_id
ORDER BY lesson_id`,
[2,10]);
但这不是预期的答案。
I am working with nodejs and postgresql. My postgresql relation has 3 columns:
- id
- lesson_id
- tag_id.
A lesson could belong to 1 or multiple tags.
I am trying to select all the lesson whose belongs to the requested tags.
For example
- tags requested are id 10 and 2, the query should response with lesson id = 3
- tags requested are id 1 and 17, the query should response with lesson id = 6
- tag requested is 3, the query should response with lessons id 1, 2, 4
I have tried some sql queries like this one:
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]);
but it's not the expected answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
不存在
喜欢这样的:很难消化,因此很少解释:
quiert quertion_tags
包含值10和2则不 nofollow noreferrer“> db<> tiddle
You can use
not exists
like so:It is difficult to digest so little explanation:
required_tags
containing values 10 and 2DB<>Fiddle