2016-04-06 6 views
-1

3つのテーブルがあるだけに、2つのテーブルから選択します:第二のテーブルに複数の条件を満たした行

  • 投稿
  • posts_tags
  • タグ

するだけのことを選択することが可能です特定のタグが2つ以上ある投稿はありますか?選択のため

特定のタグを持つすべての記事は、私がこの

SELECT * FROM posts, tags WHERE posts.id=tags.id_post AND post_tags.id_tag=1 

を行い、私はこのクエリをしようとしたが、それは私に= 2

SELECT * FROM posts, tags WHERE posts.id=post_tags.id_post AND post_tags.id_tag IN (1,2) 
+1

Joinはこの問題を解決しません@RuchishParikh – Daan

+1

@RuchishParikh、彼は既に参加しています(暗黙的なものです)。 – jarlh

+0

通常、 'posts'、' tags'、そしてどのタグが属するのかという3つのテーブルがあります例えば ​​'post_tag'を投稿する – Strawberry

答えて

1
SELECT posts.* 
FROM posts 
JOIN tags ON posts.id = tags.id_post 
WHERE tags.id IN(1, 2) 
GROUP BY posts.id 
HAVING COUNT(tags.id_post) >= 2 
= 1またはpost_tags.id_tagをpost_tags.id_tagている記事を提供します
+2

を削除してください 'ASの –

+0

タグの数ではありません。 2つ以上のCERTAINタグを持つ投稿のみを選択する必要があります。例id = 1、id = 2のタグの場合 –

+0

条件が追加されました – arhey

0

私が正しくあなたを理解していれば -

SELECT postName,count(*) as times    -- you can add fields or omit the count(*) 
FROM 
(select * from posts where id in (1,2) posts  -- you can replace the whole line with `posts`. this way gives you more room for conditions 
inner join 
(select * from tags where id_post in (1,2)) tags -- same as @posts 
on posts.id=tags.id_post 
group by postName        -- if you added some fieldNames at the first line - add them here too.. 
having times>=2 
               -- AND tags.id=1 -- you can specify more conditions here 
関連する問題