如何在mysql中自行加入多个值?

时间:2011-03-05 15:34:37

标签: mysql join self

具体来说,我想根据表格的键/值类型中的N个元值来查询单词帖子。

我根本找不到工作查询的好例子。

用简单的英语,查询就是这样。

选择所有帖子,即city = Dallas,style = ranch,价格在100k到200k之间,pool = true

我可能有更多或更少的元值我需要比较。

对于非单词印刷用户,元值位于一个表格中,每个元素与帖子表格中的帖子ID相关联。

1 个答案:

答案 0 :(得分: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'