0

我有一个表帖子,例如:

post_id | title
   1       im in Guadalajara and Zapopan
   2       im just in Guadalajara but not in Zapopan

和表 meta_keys

post_id | meta_key
  1         Guadalajara
  1         Zapopan
  2         Guadalajara

我需要同时获得瓜达拉哈拉和萨波潘的帖子,我意识到如果我与 or 进行内部连接,会给我两个

在这个例子中,我期望构造一个抛出帖子 1(只是 1)的查询

谢谢

4

2 回答 2

1

一种方法是使用双连接:

select
  *
from
  posts p
inner join meta_keys mk1 on p.post_id = mk1.post_id
inner join meta_keys mk2 on p.post_id = mk2.post_id
where
  mk1.meta_key = 'Guadalajara' and
  mk2.meta_key = 'Zapopan'
;
于 2012-06-30T15:30:11.660 回答
1

以下为您post_id提供两者中的 s

select post_id
  from meta_keys
 where meta_key in ('Guadalajara','Zapopan')
 group by post_id
having count(*) = 2

然后,您可以加入它以posts获取实际帖子:

select p.*
  from posts as p
  join ( select post_id
           from meta_keys
          where meta_key in ('Guadalajara','Zapopan')
          group by post_id
         having count(*) = 2 ) as m
    on p.post_id = m.post_id
于 2012-06-30T15:30:26.850 回答