MySQL加入和分组列

时间:2013-07-03 21:46:14

标签: mysql

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

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 |

2 个答案:

答案 0 :(得分:3)

参见COALESCE()。这就是你所需要的一切!

答案 1 :(得分: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 |