0

我有以下架构。

架构图片

我可以相当简单地运行两个查询

select *  from booking_model_assignment 
     join booking_model on booking_model_assignment.booking_model_id = booking_model.id
left outer join axis_channel_mappings on bmi_id = axis_channel_mappings.assignment_id
left outer join axis_revenue_stream_mappings on bmi_id = axis_revenue_stream_mappings.assignment_id

这将为我提供channel mappings适合预订模型的 和 'revenue_stream_mappings' 的所有组合,如果有一个仅在其中一个表中匹配的组合,则为 Null。

另一个查询

select * from axis_channel join axis_revenue_stream

提供渠道和收入流的所有可能组合。

我想要的是一个查询,它将给出所有组合,如果该组合匹配,则为 booking_model。

每当我尝试加入或子查询时,我似乎得到的结果太多或太少。我认为问题是我希望 assignment_id 跨外连接匹配,但前提是存在外连接。

架构是这样布局的,因此可以添加新轴和适合模型到组合中,所以如果有更简单的方法来实现这一点,我会愿意更改架构。

编辑

我有一个基于 Eggyal 回答的部分解决方案,但它不可扩展。

SELECT       c.*, r.*, GROUP_CONCAT(a.bmi_id), GROUP_CONCAT(b.name) AS booking_models
FROM         axis_channel                 c
CROSS JOIN axis_revenue_stream          r
LEFT JOIN axis_channel_mappings        cm ON cm.channel_id        = c.id
LEFT JOIN axis_revenue_stream_mappings rm ON rm.revenue_stream_id = r.id
LEFT JOIN booking_model_assignment     a  ON (a.bmi_id = cm.assignment_id
                                             AND a.bmi_id = rm.assignment_id)
                                             OR (a.bmi_id = cm.assignment_id
                                             AND rm.assignment_id IS NULL)
                                             OR (cm.assignment_id  IS NULL
                                             AND a.bmi_id = cm.assignment_id)
LEFT JOIN booking_model                b  ON b.id = a.booking_model_id
GROUP BY     c.id, r.id

但是如果我要添加更多的轴,这个查询会变得很麻烦。

4

1 回答 1

1
SELECT       c.*, r.*, GROUP_CONCAT(b.name) AS booking_models
FROM         axis_channel                 c
  CROSS JOIN axis_revenue_stream          r
   LEFT JOIN axis_channel_mappings        cm ON cm.channel_id        = c.id
   LEFT JOIN axis_revenue_stream_mappings rm ON rm.revenue_stream_id = r.id
   LEFT JOIN booking_model_assignment     a  ON a.bmi_id = cm.assignment_id
                                            AND a.bmi_id = rm.assignment_id
   LEFT JOIN booking_model                b  ON b.id = a.booking_model_id
GROUP BY     c.id, r.id
于 2013-10-30T13:07:41.973 回答