0

ここに契約があります - ここに 3 つのテーブルがあります。

Companies:
ID | NAME | DETAILS

TAGS
ID | TAGNAME

TAGS_COMPANIES
COMPANY_ID | TAGID

ネストされたクエリを使用して、特定のセットのタグでタグ付けされたすべての会社を取得できます。

select c.* from companies c where c.id in (select t.company_id where t.tagid in (12,43,67))

上記のクエリは、タグ ID 12、43、または 67 を持つすべての企業を返しますが、12 AND 43 AND 67 のタグが付けられたすべての企業を取得する必要があります。

ここでクエリをやり直すにはどうすればよいですか? 私はMySQLを使用しています

4

2 に答える 2

1

あまり効率的ではありませんが、機能します:

select c.* 
from companies c 
where c.id in (select t.company_id from tags_companies t where t.tagid = 12)
and c.id in (select t.company_id from tags_companies t where t.tagid = 43)
and c.id in (select t.company_id from tags_companies t where t.tagid = 67)

HAVING 句を使用した別の可能性:

select c.id, c.name, c.details
from companies c join tags_companies t on c.id = t.company_id
where t.tagid in (12, 43, 67)
group by c.id, c.name, c.details
having count(distinct t.tagid) = 3
于 2011-04-12T08:19:26.770 に答える
0

1 つのサブクエリで。

select c.* 
      from companies c  
      where (c.id, 3) in 
         (select t.company_id, count(distinct t.tagid) 
                 from tags t
           where t.tagid in (12,43,67) 
             group by t.company_id)

マジック ナンバー 3 は、異なるタグ数を意味します。

于 2011-04-12T08:29:00.793 に答える