سؤال

Hi I don't understand this simple SQL query with JOIN. I want to select product with two attributes. Here are tables (product and then attributes):

Product table

Attribute table

And here goes two queries

First query do only one join with 4 AND operators and return no data (but it should).

Second query do two join with the tables product <-> attrv_1 and product <-> attrv_2 and works very well. :

Here's the first query

SELECT * 
FROM tblProducts p 
INNER JOIN tblAttributesValues attrv ON p.productid = attrv.productid
                    AND attrv.atrid = 1
                    AND attrv.atrvalue like '%JANICKA IWONA%' 
                    AND attrv.atrid = 2
                    AND attrv.atrvalue like '%N.ERA%' 

and second query which return proper data:

SELECT p.* 
FROM tblProducts p 
INNER JOIN tblAttributesValues attrv_1 ON p.productid = attrv_1.productid
                    AND attrv_1.atrid = 1
                    AND attrv_1.atrvalue LIKE '%JANICKA IWONA%'
INNER JOIN tblAttributesValues attrv_2 ON p.ProductID = attrv_2.ProductId
                    AND attrv_2.atrid = 2
                    AND attrv_2.atrvalue LIKE '%N.ERA%'   

In the second SQL query I did twice join to find product with two attributes.

Why first query doesn't apply AND operator with one join?

Here's output:

Second query output

هل كانت مفيدة؟

المحلول

"Why first query doesn't apply AND operator with one join?"

Because there aren't any rows in attributes table which could have atrid = 1 and atrid = 2 at the same time.

I could thought of a solution which could use group by, having and count clauses to achieve desired results, but your second query would be most probably faster and simpler to understand.

نصائح أخرى

Your first query can never return any results. What you are asking it to do is get every product for which the attribute table has an entry where the atrvalue field is equal to 1 and the atrvalue field is also equal to 2. Since it has to be one of the other, this means the right hand side of your join will never have any entries, and since this is an inner join the left hand side will never be matched, hence no rows. What you actually want is an OR between your two sets of conditions:

SELECT * from tblProducts p join tblAttributesValues attrv ON p.productid = attrv.productid AND (attrv.atrid = 1 AND attrv.atrvalue like '%JANICKA IWONA%') OR (attrv.atrid = 2 AND attrv.atrvalue like '%N.ERA%')

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top