mysql将1:n关系收集到一条记录中

时间:2012-05-17 19:44:16

标签: mysql select database-relations

我有一个1:n的关系:

Rule  1:n  Examples

为简化起见,您可以假设Rule和Examples仅包含一个字符串属性。我正在寻找一个sql语句,我得到一个包含以下列的表:

rule; example_1; example_2; example_3

我不关心4和更高的例子......

1 个答案:

答案 0 :(得分:0)

我觉得有一个更好的方法可以做到这一点,我忽略了,但这似乎工作得很好。我自动加入了有序的examples表,其中每个连续的示例值必须大于前一个值(因此产生前三个中的每一个)。

SELECT
  r.rule,
  e1.example AS example_1,
  e2.example AS example_2,
  e3.example AS example_3
FROM rules r
LEFT JOIN (SELECT * FROM examples e ORDER BY example) e1
  ON e1.ruleID = r.ruleID
LEFT JOIN (SELECT * FROM examples e ORDER BY example) e2
  ON e2.ruleID = r.ruleID
  AND e2.example > e1.example
LEFT JOIN (SELECT * FROM examples e ORDER BY example) e3
  ON e3.ruleID = r.ruleID
  AND e3.example > e2.example
GROUP BY r.ruleID

结果:

|  RULE | EXAMPLE_1 | EXAMPLE_2 | EXAMPLE_3 |
|-------|-----------|-----------|-----------|
| rule1 |       ex1 |       ex2 |       ex3 |
| rule2 |       ex5 |       ex6 |       ex7 |
| rule3 |       ex8 |    (null) |    (null) |
| rule4 |    (null) |    (null) |    (null) |

示例数据:

/* rules table */
| RULEID |  RULE |
|--------|-------|
|      1 | rule1 |
|      2 | rule2 |
|      3 | rule3 |
|      4 | rule4 |

/* examples table */
| EXAMPLE | RULEID |
|---------|--------|
|     ex1 |      1 |
|     ex2 |      1 |
|     ex3 |      1 |
|     ex4 |      1 |
|     ex5 |      2 |
|     ex6 |      2 |
|     ex7 |      2 |
|     ex8 |      3 |

这是一个有效的SQL Fiddle example