Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL连接和分组列_Mysql - Fatal编程技术网

MySQL连接和分组列

MySQL连接和分组列,mysql,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'

在下面的情况下,我需要以某种方式将一些列组合成一个列。我有以下疑问:

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  |
+--------+--------+--------+--------+
这是一个包含220000多行的类别表

我需要最后一个id(不为空)。所以在这种情况下,我需要(253819841)

最简单的方法是什么

最好的结果应该是:

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

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

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

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

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 |

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

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 |

请告诉我们你的预期结果。很难猜出你想要什么。请告诉我们你的预期结果。很难猜出你想要什么。正确,非常感谢!将顺序稍微更改为
合并(f.id,e.id,d.id,c.id,b.id,a.id)为id
正确,非常感谢!将顺序稍微更改为
COALESCE(f.id,e.id,d.id,c.id,b.id,a.id)作为id