2011-03-05 15 views
0

具体的には、テーブルのキー/値タイプにあるN個のメタ値に基づいてワードプレスの投稿を照会します。mysqlの複数の値を自己結合する方法は?

私は単に動作中のクエリの良い例を見つけることができません。

普通の英語では、クエリは次のようになります。

私はと比較する必要が多かれ少なかれメタ値を有することができる都市=ダラス、スタイル=牧場、100K and200k間の価格、プール=真

ことをすべての記事を選択します。

非ワードプレスユーザーの場合、メタ値は1つのテーブルにあり、各メタは投稿テーブルの投稿IDに関連付けられています。

答えて

3

ああ、EAVの喜び。つまり、複数のサブクエリまたはクロス集計を実行する必要があります。

Select ... 
From Posts 
Where post_id In (
        Select post_id 
        From Meta 
        Where Attribute = 'City' 
         And Value = 'Dallas' 
        ) 
    And post_id In (
        Select post_id 
        From Meta 
        Where Attribute = 'Style' 
         And Value = 'Ranch' 
        ) 
    And post_id In (
        Select post_id 
        From Meta 
        Where Attribute = 'Price' 
         And Cast(Value As int) Between 100000 And 200000 
        ) 
    And post_id In (
        Select post_id 
        From Meta 
        Where Attribute = 'Pool' 
         And Value = 'True' 
        ) 

ここでは、クロスタブを作成する別のフォームを示します。それはよりコンパクトですが、同様に動作しない可能性があります:

Select ... 
From Posts As P 
    Join (
      Select post_id 
       , Min(Case When Attribute = 'City' Then Value End) As City 
       , Min(Case When Attribute = 'Style' Then Value End) As Style 
       , Min(Case When Attribute = 'Price' Then Cast(Value As int) End) As Price 
       , Min(Case When Attribute = 'Pool' Then Value End) As Pool 
      From Meta 
      Where Attribute In('City','Style','Price','Pool') 
      Group By post_id 
      ) As Attributes 
     On Attributes.post_id = P.post_id 
Where Attributes.City = 'Dallas' 
    And Attributes.Style = 'Ranch' 
    And Attributes.Price Between 100000 And 200000 
    And Attributes.Pool = 'True' 
+0

ありがとう!私のために働く! –

関連する問題