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

标签 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

预期输出

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

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 = ''

到目前为止我的工作可以在这个 sqlfiddle 中看到:

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

我使用的 SQL 查询

来自 fiddle 。

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 但这只会删除必要的数据。

最佳答案

试试这个

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')

关于多态关联连接的 MySQL 错误 id 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36593608/

相关文章:

mysql - SQL查询: BETWEEN

mysql - 如何根据另一个表过滤结果。 (我猜是反向连接?)

mysql - SQL 对一列中不同值的日期计数

ruby-on-rails - 如何在 Rails 2.3 中测试多态 Controller ?

ruby-on-rails - Rails 多态 child

mysql - linux命令行根据mysql结果集压缩文件

mysql - Symfony2 和 Doctrine Mysql 测试数据库 Persist

mysql - DELETE CASCADE MySQL 最佳实践

MySQL 查询不会停止运行

relational-database - 在关系数据库中表示多态关联的最佳方式是什么?