内连接取决于行

时间:2012-06-30 15:24:09

标签: mysql sql

我有一个表格帖子,例如:

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

我需要获得Guadalajara和zapopan中的帖子,我知道如果我用or进行内部联接,将会给我两个

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

由于

2 个答案:

答案 0 :(得分: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'
;

答案 1 :(得分:1)

以下内容为您提供了两者中的post_id

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