0

i have 3 tables, that form a many-to-many relationship between [monsters] and [types]

monsters, monsters_types, types

i have the following monsters with several related [types] each

MONSTERS.name  |  TYPES.name
===============|===============
sharkthing     |  fish
sharkthing     |  human
               |
werewolf       |  human
werewolf       |  wolf
werewolf       |  warrior
               |
blob           |  ooze
               |
thefly         |  insect
thefly         |  human

I want to find all monsters that have a have a relationship with the type "(wolf or insect) AND (human)", so with that expression i want to get

MONSTERS.name   
===============
werewolf       
thefly        

here's my query below:

SELECT monsters.name from monsters
JOIN monsters_types
ON monsters_types.monster_id = monster.id
JOIN types
ON types.id = monsters_types.type_id
WHERE (types.name = 'wolf' OR types.name = 'insect') AND types.name = 'human'

this won't work because there's an AND operator the type.name field can't be both 'human' and something else at the same time.

I've looked into using IN statments but that doesn't work well for me due to the fact that I'm building queries dynamically based on expressions passed in. For the above table an example url would be

www.example.com/listmonsters?type=(wolf|insect),human

is it possible to select all [monsters] that have the related [types] specified by a complex expression?

4

1 回答 1

0

尝试:

SELECT DISTINCT monsters.name
FROM   monsters
       JOIN monsters_types
         ON monsters_types.monster_id = monster.id
WHERE  EXISTS (SELECT *
               FROM   types
               WHERE  types.id = monsters_types.type_id
                      AND type.name IN ( 'wolf', 'insect' ))
       AND EXISTS (SELECT *
                   FROM   types
                   WHERE  types.id = monsters_types.type_id
                          AND type.name = 'human')
于 2013-06-19T08:29:01.457 回答