Possible Duplicate:
How to select rows where multiple joined table values meet selection criteria?
I have a Users table, and an Optons table which contains some options for each user. Each user can have multiple options selected.
This is how tables look like:
-- this is where user names are stored
create table Users
(
ID int,
UserName varchar(255)
)
-- this table contains options
-- (one flag per row)
create table Options
(
ID NOT NULL AUTO_INCREMENT int,
Flag int,
User_ID int // foreign key
)
I would like to get all users which have two certain options set, but only if both of them are set.
For example, this will return users where any of the options is set:
-- find all users with flags 1 and 2 set
select u.UserName from Users u
inner join Options o on o.User_ID = u.ID
where o.Flag in (1, 2)
How can I make it return all users which have two entries (for flags 1 and 2) in the Options table?
Your query is almost correct but you need to count the number instances of the records and should be equal to the number of parameters in your
whereclause.