0

在以下情况下,我需要以某种方式将一些列组合为一个。我有以下查询:

SELECT a.id,b.id,c.id,d.id
FROM some_table AS a
LEFT JOIN some_table AS b ON ( a.id=b.parent_id )
LEFT JOIN some_table AS c ON ( b.id=c.parent_id )
LEFT JOIN some_table AS d ON ( c.id=d.parent_id )
WHERE a.id = '22'

结果是:

+--------+--------+--------+--------+
|  a.id  |  b.id  |  c.id  |  d.id  |
+--------+--------+--------+--------+
|    22  |    24  |    25  |  null  |
|    22  |   381  |  null  |  null  |
|    22  |   418  |  2389  |  9841  |
+--------+--------+--------+--------+

这是一个包含 220,000 多行的类别表。

我需要最后一个 id(不是 NULL)。所以在这种情况下我需要 (25,381,9841)

实现这一目标的最简单方法是什么?

最好的结果应该是:

+------+
|   id |
+------+
|   25 |
|  381 |
| 9841 |
4

2 回答 2

3

请参阅 COALESCE()。这就是你所需要的!

于 2013-07-03T22:00:17.463 回答
1

要扩展上述答案,您似乎需要

SELECT a.id, COALESCE(d.id, c.id, b.id) AS 'id'
FROM some_table AS a
LEFT JOIN some_table AS b ON ( a.id=b.parent_id )
LEFT JOIN some_table AS c ON ( b.id=c.parent_id )
LEFT JOIN some_table AS d ON ( c.id=d.parent_id )
WHERE a.id = '22'

这会给你一个输出

+------+------+
| a.id |   id |
+------+------+
|   22 |   25 |
|   22 |  381 |
|   22 | 9841 |
于 2013-07-03T22:06:00.800 回答