1

こんにちは私はこの単純なSQLクエリを理解していませんJOIN。2つの属性を持つ製品を選択したいと思います。テーブル(製品、次に属性)は次のとおりです。

製品表

属性テーブル

そしてここに2つのクエリがあります

最初のクエリは、4つのAND演算子を使用して1つの結合のみを実行し、データを返しません(ただし、そうする必要があります)。

2番目のクエリは、テーブルproduct<->attrv_1およびproduct<->attrv_2と2つの結合を実行し、非常にうまく機能します。:

これが最初のクエリです

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%' 

適切なデータを返す2番目のクエリ:

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%'   

2番目のSQLクエリでは、2回結合して、2つの属性を持つ製品を検索しました。

最初のクエリが1つの結合でAND演算子を適用しないのはなぜですか?

出力は次のとおりです。

2番目のクエリ出力

4

2 に答える 2

2

"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.

group by、have、count句を使用して目的の結果を達成できるソリューションを考えることもできますが、2番目のクエリの方がおそらく高速で理解しやすいでしょう。

于 2011-09-08T10:39:48.590 に答える
1

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%')

于 2011-09-08T10:16:08.937 に答える