MySQL错误的id返回多态关联连接

时间:2016-04-13 09:08:05

标签: mysql sql polymorphic-associations

我与两个表有多态关联。 (我知道它一团糟,但我将不得不暂时离开)

在使用主表查询时,我需要连接两个表的结果。我接近我想要的结果但主表id在我的情况下返回错误。

数据结构

Table A
    |-- id
    |-- type
    |-- type_id
    |-- property_a1
    |-- property_a2



Table B
    |-- id
    |-- property_b1
    |-- property_b2


Table C
    |-- id
    |-- property_c1
    |-- property_c2

预期产出

我想要下面的结果。每行包含所有三个表的所有字段(或按查询选择)。如果给定关联表中缺少属性,则分配空字符串或空字符串。

Result Row
    |-- id
    |-- property_a1
    |-- property_a2

    |-- type
    |-- type_id

    |-- property_b1 // if property from Table c value = ''
    |-- property_b2 // if property from Table c value = ''


    |-- property_c1 // if property from Table b value = ''
    |-- property_c2 // if property from Table b value = ''

到目前为止,我的工作可以在这个方面看到:

http://sqlfiddle.com/#!9/2d05e/17

我使用的SQL查询

来自小提琴。

SELECT
  product.id,
  res.name,
  res.fruit_id,
  res.vegetable_id,
  res.is_green,
  res.color,
  product.price,
  res.seasonal
FROM
  product
JOIN
  (
  SELECT
    fruit.id AS fruit_id,
    0 AS vegetable_id,
    fruit.name,
    fruit.color,
    fruit.seasonal,
    false as is_green
  FROM
    fruit

  UNION
SELECT
    0 as fruit_id,
    vegetable.id AS vegetable_id,
    vegetable.name,
    '' as `color`,
    false as `seasonal`,
    vegetable.is_green
  FROM
    vegetable

) res ON product.type_id = res.fruit_id OR product.type_id = res.vegetable_id

我可以使用GROUP BY但只删除必要的数据。

1 个答案:

答案 0 :(得分:1)

试试这个

<强> SQl Fiddle Demo

SELECT product.id, res.name, res.fruit_id, res.vegetable_id,
  res.is_green,res.color,product.price,res.seasonal
FROM product
JOIN
  (
  SELECT fruit.id AS fruit_id,
    0 AS vegetable_id,fruit.name,fruit.color,fruit.seasonal,
    false as is_green
  FROM fruit      
  UNION
  SELECT 0 as fruit_id,vegetable.id AS vegetable_id,
    vegetable.name,'' as `color`,false as `seasonal`, vegetable.is_green
  FROMvegetable      
) res ON (product.type_id = res.fruit_id  AND product.product_type = 'fruit')
      OR (product.type_id = res.vegetable_id AND product.product_type = 'vegetable')