繁体   English   中英

我如何在mysql中对多个值进行自我联接?

[英]How do I self join on multiple values in mysql?

具体来说,我想基于表的键/值类型中的N个元值查询新闻发布。

我只是找不到一个有效的查询示例。

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

选择所有城市=达拉斯,风格=牧场,价格在100k和200k之间,pool = true的帖子

我可能需要比较一些或更少的元值。

对于非wordpress用户,元值位于一个表中,每个元数据都与posts表中的post ID相关联。

啊,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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM