select data from a table and it satisfy two conditions

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
nmreddy
Forum Commoner
Posts: 25
Joined: Wed Feb 18, 2009 5:36 am

select data from a table and it satisfy two conditions

Post by nmreddy »

i have a table of data like this with four columns(id1,id2,keyname,keyvalue)

id1 id2 keyname keyvalue

1 -- 111 -- a -- 2

2 -- 111 -- b -- 3

3 -- 222 -- a -- 2

4 -- 222 -- b -- 4


how can i get the id2 value = 111

i written this query

select id2 from table where (a=2) and (b=3)

but it giving empty result.

can any one suggest me the better solution ?

when i placed (or) in between the conditions it giving result but i need to satisfy both conditions
tech603
Forum Commoner
Posts: 84
Joined: Thu Mar 19, 2009 12:27 am

Re: select data from a table and it satisfy two conditions

Post by tech603 »

select id2 from table where (a=2) and (b=3)
That would do it, but then if you had any other rows that had 111 in it then you would never get the proper results. From looking at your table set up

Code: Select all

id1 id2 keyname keyvalue
 
1 -- 111 -- a -- 2
 
2 -- 111 -- b -- 3
 
3 -- 222 -- a -- 2
 
4 -- 222 -- b -- 4
 
 
/* this would return all rows that had that value */
select * from table where id2 = 111
 
Hope that helps.
nmreddy
Forum Commoner
Posts: 25
Joined: Wed Feb 18, 2009 5:36 am

Re: select data from a table and it satisfy two conditions

Post by nmreddy »

yes, i have other rows with id2 as 111 like

id1 id2 keyname keyvalue

1 -- 111 -- a -- 2

2 -- 111 -- b -- 3

3 -- 222 -- a -- 2

4 -- 222 -- b -- 4

5 -- 111-- d -- 6


Here i have to get id2 value which is 111 ,with the given conditions of (a=2) and (b=3)

how can i write the query ?

Thanks,
NMreddy
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

Re: select data from a table and it satisfy two conditions

Post by susrisha »

Code: Select all

 
 
select * from tbl where id2 =111 AND ((keyname ='a' and keyvalue='2') OR (keyname='b' and keyvalue='3'));
 
nmreddy
Forum Commoner
Posts: 25
Joined: Wed Feb 18, 2009 5:36 am

Re: select data from a table and it satisfy two conditions

Post by nmreddy »

here i have to get id2 value and it satisfy both conditions ((keyname ='a' and keyvalue='2') AND (keyname='b' and keyvalue='3'))
Post Reply