tags:

views:

91

answers:

4

Consider:

SELECT id_post FROM post_property WHERE id_property = 1 AND id_property = 2

Sure you're thinking to use IN()

SELECT id_post FROM post_property WHERE id_property IN (1,2)

But that give me 2 rows as result, and I just need to get all the id_post that matched with the 2 properties

Thanks a lot for your time!

+1  A: 

id_property IN (1, 2)

is equivalent to

id_property = 1 OR id_property = 2

NOT this:

id_property = 1 AND id_property = 2.

Daniel Liuzzi
Thank you :)The solution is IN (1 AND 2)
Sanbor
I'm quite sure that *isn't* the solution you really want.
Greg Hewgill
Not really sure what you are trying to achive, but I never seen an AND clause nested inside an IN :-/
Daniel Liuzzi
The expression IN (1 AND 2) is equivalent to IN (0), because it's a bitwise AND.
Greg Hewgill
If you want to allow multiple properties to be set on a given record, and those properties where integers like your example, you could try storing those concatenating those integers in a nvarchar field using some kind of delimiter in between, like this "|1|2|". Then you can look records matching both conditions like this WHERE id_property LIKE '%|1|%' AND id_property LIKE '%|2|%'.
Daniel Liuzzi
You're right U.UConsider that I need the post that has 2 properties
Sanbor
+2  A: 

Using the where clause id_property = 1 AND id_property = 2 will never give you any rows because you're asking for all the rows where id_property equals two different things at the same time. Read the query as:

WHERE (id_property = 1 AND id_property = 2)

instead of

WHERE id_property = 1 AND (those rows where) id_property = 2

It sounds like you want to use OR, but this is equivalent to the query using IN that you have shown. If this doesn't return the rows you want, which rows do you want?

Greg Hewgill
+1  A: 

Assume your schema is something like

table post_property (id_property (FK), id_post (FK))

What if the id_property is associated with more than one id_post or the two id_properties are associated with different id_post. Then you would need both records and that is what is being returned. If you want to increase the propert_id in the where and extend the question you are asking is "what post ids do I need to look at?" then what you want is:

Select distinct id_post
from post_property
where id_property in (1,2)
David McEwing
Not worked, because returns whats match with 1 OR 2, just avoid to show the id_post twice
Sanbor
+1  A: 

SELECT id_post, count(*) as cnt FROM post_property WHERE id_property IN (1,2) group by id_post having cnt = 2

shantanuo
Finally, this REALLY works, thanks alot
Sanbor