【问题标题】:connecting tables through split fields通过拆分字段连接表
【发布时间】:2015-04-06 11:00:54
【问题描述】:

我有两张桌子; - Items 表 - 包含有关产品的基本信息:名称、产品的基本价格以及产品是否具有任何属性 - 它们将在此处以以下格式指定:属性的选项 ID - 属性的值 ID。 (选项的示例是颜色或大小,值的示例是红色)。 例如:

项目表

id  | name  |attributes |price
1   |   a   |13-49      | 5.00
2   |   b   |5-101,13-77| 5.00
3   |   c   |           | 5.00
4   |   b   |5-102,13-70| 5.00
  • 第二个表包含分配给产品的每个选项和值(id_option 和 id_value - 与上表中的含义相同)以及属性值是否更改产品的基本价格(更改)以及更改内容的信息应该是(值)。

items_attributes

id  |id_item|id_option|id_value |change | value  
1   |   1   |   13    | 49      |   1   |10.00
2   |   2   |   5     | 101     |   1   | 5.50
3   |   2   |   13    | 77      |   1   | 0.50
4   |   4   |   5     | 102     |   0   |    0
5   |   4   |   13    | 70      |   1   | 1.00

我想要一个和第一个一样的桌子,但是价格是根据items_attributes表中记录的变化计算的。

id  | name  |attributes | price
1   |   a   |13-49      | 15.00
2   |   b   |5-101,13-77| 11.00
3   |   c   |           |  5.00
4   |   b   |5-102,13-70|  6.00

如何从 items 表中拆分属性并使用它来连接两个表?

【问题讨论】:

  • 修复您的数据结构以具有联结表。 SQL 具有用于存储列表的出色数据结构。它被称为“表”,而不是“字符串”。
  • 是的,我知道。这是我得到并且必须使用的结构(由其他人提供)。

标签: mysql join split


【解决方案1】:

您可以使用find_in_set() 进行连接:

select i.id, i.name, i.attributes,
       i.price + coalesce(sum(ia.value)) as price
from items i left join
     items_attributes ia
     on find_in_set(concat(ia.id_option, '-', ia.id_attribute), i.attributes) > 0
group by i.id;

很遗憾,您无法使用索引来提高此查询的性能。为了获得更好的性能,您需要更好的数据结构。

【讨论】:

  • 小改款后:select i.id, i.name, i.attributes, i.price + IFNULL(coalesce(sum(ia.value)),0) as price from items i left join items_attributes ia on find_in_set(concat(ia.id_option, '-', ia.id_value), i.attributes) > 0 group by i.id;
猜你喜欢
  • 2013-08-28
  • 1970-01-01
  • 2011-12-05
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
  • 2011-10-07
相关资源
最近更新 更多