Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fetch query results with multiple criteria?

Tags:

sql

mysql

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.

like image 294
nkorf Avatar asked Dec 06 '25 03:12

nkorf


1 Answers

You should use an OR between your different criteria.

SELECT userid 
FROM table 
WHERE (fieldid=817 AND fieldvalue='yes')
    OR (fieldid=818 AND fieldvalue='no')

The difference between using AND/OR

The AND operator displays a record if both the first condition and the second condition is true.

The OR operator displays a record if either the first condition or the second condition is true.

EDIT: Based on your comments you can do it the following way

select t1.userid 
FROM temp t1
where (t1.fieldid=817 AND t1.fieldvalue='yes') 
    AND EXISTS (SELECT userid 
            FROM temp t 
            WHERE t.userid =  t1.userid 
                AND fieldid=818 
                AND fieldvalue='no') 

see a sqlfiddle with a working copy

or even this way

select t1.userid 
FROM temp t1
left join temp t2
    on t1.userid = t2.userid
where (t1.fieldid=817 AND t1.fieldvalue='yes')
    AND t2.fieldid=818 AND t2.fieldvalue='no'

here is another sqlfiddle

if you had more fields that you wanted to join on, then you would do the following:

select t1.userid 
FROM temp t1
left join temp t2
    on t1.userid = t2.userid
left join temp t3
    on t1.userid = t3.userid
where (t1.fieldid=817 AND t1.fieldvalue='yes')
    AND (t2.fieldid=818 AND t2.fieldvalue='no')
    AND (t3.fieldid=819 AND t3.fieldvalue='no')
like image 51
Taryn Avatar answered Dec 08 '25 16:12

Taryn