我有一个数据库,其中一个user有多个submission,一个submission有多个post
我想找到所有的用户谁做了标签“汽车”和标签“自行车”的帖子。
下面是我尝试过的查询,它找不到标签为“car”和“bike”的帖子

select distinct u.*
from users u
         inner join submission s on u.name = s.user_name
         inner join post rp on s.id = rp.submission_id
where rp.tag = 'card' and rp.tag = 'bike'

我该如何正确地构造这个查询,以便它返回那些用“car”标记发帖子和用“bike”标记发帖子的用户?

最佳答案

如果只需要名称,可以尝试使用count distinct=和tag=card或tag=bike检查用户

select  u.name
from  users
inner join submission s on u.name = s.user_name
inner join post rp on s.id = rp.submission_id
where rp.tag = 'car' OR rp.tag = 'bike'
group by u.name
having count(distinct  rp.tag) = 2

如果你需要所有的用户信息,你应该和用户一起加入这个结果
select u.*
from users u
inner  join  (
  select  u.name
  from  users
  inner join submission s on u.name = s.user_name
  inner join post rp on s.id = rp.submission_id
  where rp.tag = 'car' OR rp.tag = 'bike'
  group by u.name
  having count(distinct  rp.tag) = 2
) t on t.name  = u.name

关于sql - SQL查找子项在多行上匹配的父项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57534369/

10-12 07:16