将表多次连接到另一个可能具有或不具有这些值的表
我有三个表:
| items
--------
id
quantity
size_attribute_value_id
color_attribute_value_id
type_attribute_value_id
| attribute_values (instance of an attribute, like red, xsmall)
--------
id
attribute_id
name
| attributes (attribute category, like color, size)
id
name
三个属性(大小、颜色、类型)的任意组合都可以生成有效的项目。因此,我希望能够查询这三个属性的所有组合,同时还包括项目表中现有的项目。我的想法是我想要一个包含所有现有项目和所有可能的有效未来项目的结果集。例如,即使 items 表完全空白,我仍然应该得到数量为 0 的不存在但有效的项目的结果。
有效的 attribute_ids 为 1、2、4。
我尝试了以下右连接作为开始:
SELECT i.*, av1.*, av2.*, av3.*
FROM items i
RIGHT OUTER JOIN attribute_values av1 ON av1.attribute_id = 2 AND av1.id = i.size_attribute_value_id
RIGHT OUTER JOIN attribute_values av2 ON av2.attribute_id = 4 AND av2.id = i.color_attribute_value_id
RIGHT OUTER JOIN attribute_values av3 ON av3.attribute_id = 1 AND av3.id = i.type_attribute_value_id;
但它只返回大约 200 行,而实际应该超过 1000 行。
任何帮助,即使只是正确方向的一点,我们都会表示赞赏。
I have three tables:
| items
--------
id
quantity
size_attribute_value_id
color_attribute_value_id
type_attribute_value_id
| attribute_values (instance of an attribute, like red, xsmall)
--------
id
attribute_id
name
| attributes (attribute category, like color, size)
id
name
Any combination of the three attributes (size, color, type) can make a valid item. Therefore, I want to be able to query for all combinations of the three attributes, while also including already existing items from the items table. The idea being I want a result set of all existing items and all possible valid future items. For example, even if the items table is completely blank, I should still get results of non-existent but valid items with quantities of 0.
Valid attribute_ids are 1, 2, 4.
I've tried the following right join as a start:
SELECT i.*, av1.*, av2.*, av3.*
FROM items i
RIGHT OUTER JOIN attribute_values av1 ON av1.attribute_id = 2 AND av1.id = i.size_attribute_value_id
RIGHT OUTER JOIN attribute_values av2 ON av2.attribute_id = 4 AND av2.id = i.color_attribute_value_id
RIGHT OUTER JOIN attribute_values av3 ON av3.attribute_id = 1 AND av3.id = i.type_attribute_value_id;
But it's only returning about 200 rows, when it should be more over 1000.
Any help, even if just a point in the right direction, is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这假设您的项目表中除了类型、尺寸和颜色之外还有很多其他属性,并且可能有更多列,如果没有,最好将属性放在单独的表中,例如类型、颜色和尺寸,当数据库变大时,这将更容易查询,并通过适当的索引为您带来显着的性能改进。
This assumes you have also a lot of other attributes other than type, size and color and possibly more columns in your items table, if you don't it would be much better to put attributes in separate tables, like types, colors and sizes, which would be easier to query and give you noticeable performance improvement with proper indexing when your database grows big.
我认为这应该可以做到 -
我已经重写了这个查询以避免派生表。它应该表现得更好。
I think this should do it -
I have rewritten this query to avoid the derived tables. It should perform better.