2

我有一个 1:n 的关系:

Rule  1:n  Examples

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

rule; example_1; example_2; example_3

我不在乎示例 4 及更高版本...

4

1 回答 1

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 示例

于 2012-05-17T20:35:25.643 回答