I have a table like this
Table
-----
userid
fieldid
fieldvalue
where userid and fieldid are the primary key pair for this table.
I want to make an sql query that finds all users that have fieldvalue equal to something for a selected fieldid
For example, for the values
fieldid: 817
fieldvalue: 'yes'
I can have an sql query like:
select userid FROM table where (fieldid=817 AND fieldvalue='yes')
This query works fine.
However if i have a second or a third criterion, making the query
like this:
select userid
FROM table
where (fieldid=817 AND fieldvalue='yes')
AND (fieldid=818 AND fieldvalue='no')
returns an empty result but the conditions are satisfied in the
individual criterion.
Is there any way to correct this ?
update
i forgot to write down a use case (appologies)
userid, fieldid, fieldvalue
1 , 817, yes
1, 818, no
1, 825, yes
2, 817, yes
2, 818, yes
3, 829, no
for this table i want an sql query that finds the users that have the following conditions satisfied : The fieldid 817 has a value of yes and the fieldid 818 a value of no
Using the OR suggestions i had so far satisfied either the fieldid 817 to have a value of yes OR the fieldid 818 to have a value of no
I want both conditions to be satisfied. In the above the expected result will be
userid
1
and not
userid
1
2
Since userid 2 doesn’t satisfy both conditions. Apologies for the confusion.
You should use an
ORbetween your different criteria.The difference between using
AND/OREDIT: Based on your comments you can do it the following way
see a sqlfiddle with a working copy
or even this way
here is another sqlfiddle
if you had more fields that you wanted to join on, then you would do the following: