SQL:根据其属性查找项目
在PostgreSQL上,我有一个表项目和一个table item_attribute。因此,项目可以具有多个属性。
表:项目
ID | 名称 |
---|---|
1 | A |
2 | B |
3 | C |
表:Item_Attribute
ID | ITEM_ID | 名称 | 值 |
---|---|---|---|
1 | 1 | FOO | bar |
2 | 1 | size | m |
3 | 1 | country | de |
4 | 2 | foo | baz |
5 | 2 | size | m |
6 | 2 | Country | de |
7 | 3 | 其他 | 测试 |
8 | 3 3 | 尺寸 | m |
9 | 3 | Country | 现在 |
,我需要找到与给定属性的名称/值对匹配的项目
,因此,假设我想找到带有 country
带有值 de de country
属性的项目代码>和 size
带有值 m
结果集应为
ID | 名称 |
---|---|
1 | A |
2 | B, |
如果我想找到带有 country> country
的项目值 en
和 size
带有值 m
结果集应
ID | 名称 |
---|---|
3 | C。 |
为
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用聚合方法,我们可以尝试:
上述使用条件聚合以中等大小的饮食项目。
Using an aggregation approach we can try:
The above uses conditional aggregation to find items from Germnay in medium size.
您可以在“ item_attribute ”表中找到满足您条件的所有“ item_id ”之间的交点,然后匹配“ item “表。
您可以在“ filtered_ids ” CTE中堆叠尽可能多的条件。
检查演示在这里。
You can find the intersection between all "item_id"s that satisfy your conditions inside the "item_attribute" table, then match the corresponding value inside the "item" table.
You can stack as many conditions as you want inside the "filtered_ids" cte.
Check the demo here.
一个选项是将属性汇总到JSON值中,并使用功能非常强大的要找到这些项目,
我不确定这比计数的传统方法更快还是慢(请参阅Tim Biegeleisen的答案)。不过,这更灵活。
根据数据分配,对所有项目进行一次聚合可能更快:
这也使结果可以在结果的列中显示所有属性(作为JSON)。
One option is to aggregate the attributes into a JSON value and use the quite powerful JSON operators to find the items
I am not not sure if this is faster or slower than the traditional approach with counting (see Tim Biegeleisen's answer). It is a bit more flexible though.
Depending on the data distribution, doing the aggregation once for all items might be faster:
This also enables to display all attributes (as JSON) in a column of the result.