具体来说,我想根据键/值类型表中的 N 个元值来查询 word press 帖子。
我根本找不到工作查询的好例子。
用简单的英语,查询将是这样的。
选择 city=Dallas、style=ranch、price 在 100k 到 200k 之间、pool=true 的所有帖子
我可能有或多或少需要比较的元值。
对于非文字媒体用户,元值位于一个表中,每个元都与来自帖子表的帖子 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'