MySQL加入自我类似的领域

时间:2012-06-27 00:04:23

标签: mysql self-join

在我们开始之前,不要怪我,我没有设计数据库。我很清楚,必要时可以添加列。

考虑一下mySQL的这个片段:

SELECT r.id,
   crf.field_name,
   crf.field_value
FROM reports r
   JOIN custom_report_fields crf
     ON crf.report_id = r.id
WHERE r.id IN ( 100, 101 )
   AND field_name LIKE "service_%"  

这会产生这些无益的结果:

ID   | field_name     | field_value
------------------------------------------------
100  | service_id_1   | 20
100  | service_name_1 | "Shipping"
100  | service_cost_1 | 5.25
101  | service_id_1   | 21
101  | service_name_1 | "Handling"
101  | service_cost_1 | 7.50
101  | service_id_2   | 20
101  | service_name_2 | "Shipping"
101  | service_cost_2 | 7.75

我需要一个能产生这些结果的查询:

Report ID | Field ID | Name       | Cost
------------------------------------------------
100       | 20       | "Shipping" | 5.25
101       | 21       | "Handling" | 7.50
101       | 20       | "Shipping" | 7.75

请注意,报告可能会产生任意数量的费用,每个连续的费用会获得另外三个条目和一个增加的后缀(' service_id_x',' service_name_x',&# 39; service_cost_x&#39)

这个问题的回答者将比你所选宗教的其他追随者获得更好的来世。

1 个答案:

答案 0 :(得分:2)

试试这个解决方案。它非常笨重(鉴于设计本身的笨重性,它只能是如此优雅!),但它有效:

SELECT
    a.id AS Report_ID,
    MAX(CASE WHEN b.field_name LIKE 'service_id_%' THEN b.field_value END) AS Field_ID,
    MAX(CASE WHEN b.field_name LIKE 'service_name_%' THEN b.field_value END) AS Name,
    MAX(CASE WHEN b.field_name LIKE 'service_cost_%' THEN b.field_value END) AS Cost
FROM
    reports a
INNER JOIN
    custom_report_fields b ON a.id = b.report_id
WHERE
    a.id IN (100, 101) AND
    b.field_name LIKE 'service_%'
GROUP BY
    a.id,
    SUBSTRING_INDEX(b.field_name, '_', -1)