views:

34

answers:

2

It seems complicated (and probably it is). But i cant imagine how to solve this.

There are tables:

COMPANIES
id | name
1 | Google
2 | Samsung
3 | Microsoft

PARAGRAPHS
id | name
1 | Header
2 | Body
3 | Footer

TAGS
id | tag
1 | Internet
2 | Softwate

COMPANIES_VS_TAGS
id | company_id | tag_id
1 | 1 | 1
2 | 2 | 2
3 | 3 | 1
4 | 3 | 2

PARAGRAPHS_VS_TAGS
id | paragraph_id | tag_id
1 | 2 | 1
1 | 2 | 2

I need to select all companies, that belongs to [any_number] of tags that belongs to paragraph by logical AND.

So, in the example above, the Body paragraph should output the only company "Microsoft".

ADD: I can use only WHERE and SubQueries: this is the limitation of CMS i have to use.

+1  A: 

Learn how INNER JOIN works.

http://dev.mysql.com/doc/refman/5.1/en/join.html
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

zerkms
I forgot to mention (SORRY) - I can use only WHERE and subqueries. This is the limitation of the cms i have to use.
admit
A: 

You just need to join all your tables:

SELECT companies.id, 
       companies.name 
FROM   companies, 
       tags, 
       companies_vs_tags, 
       paragraphs_vs_tags 
WHERE  companies.id = companies_vs_tags.company_id 
       AND tags.id = companies_vs_tags.tag_id 
       AND tags.id = paragraphs_vs_tags.tag_id 
       AND paragraphs.id = paragraphs_vs_tags.paragraph_id 
       AND paragraphs.name = "Microsoft"; 
Anax
Soory, but this query (minus last line) produces logical **OR**, so as a reasult I'm getting all the companies(((
admit
I need the company that have **BOTH** tags at the same time
admit