I have a case like the following picture
Say I have 9 polygons, and want to get a polygon that is maximum neighbors with 3 other polygons such as polygons 1, 3, 7, 9 (yellow)
I think this is done using ST_Touches in postgis, but I just come up with represent it in postgis code like
select a.poly_name, b.poly_name from tb a, tb b where ST_Touches(a.geom, b.geom)
And say I want to output this like:
poly_name poly_name
1 2
1 4
1 5
So how I get idea to done with this?

Your hint with
ST_Touchesis correct, however to get the amount of neighbor cells from one column related to other records in the same table you either need to run a subquery or call the table twice in theFROMclause.Given the following grid on a table called
tb.... you can filter the cells with three neighbor cells or less like this:
If you want to also list which are the neighbor cells you might wanna first join the cells that touch in the
WHEREclause and in a subquery orCTEcount the results:Demo:
db<>fiddleFurther reading:
Create Hexagons(maybe relevant for your project)Window Functions