SQL如何根据多行条件选择一个id

发布于 2025-01-17 23:49:17 字数 819 浏览 3 评论 0原文

我正在与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.

relation picure

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

非要怀念 2025-01-24 23:49:17

您可以使用不存在喜欢这样的:

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
    )
)

很难消化,因此很少解释:

  • 有一个值的构造函数,称为quiert quertion_tags包含值10和2
  • 2 存在2个课程。
  • 如果内部查询不产生匹配选择的外排,

则不 nofollow noreferrer“> db<> tiddle

You can use not exists like so:

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
    )
)

It is difficult to digest so little explanation:

  • There is a table valued constructor called required_tags containing values 10 and 2
  • The inner query tests if 10 or 2 do not exist for a lesson from the outer query
  • If the inner query does not produce a match the outer row selected

DB<>Fiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文