Skip to content
Advertisement

Postgresql: Get columns of other table as array in a object as a column with condition

i have 2 tables, servers and virtual_machines. I want to see the virtual_machines as array in the servers where serverName equals the servers name

Like this

I have servers tables

and virtual_machines tables

I tried many options like bellow but i cant make object array in colum and postgre always add key into object.

Thanks for any help

Advertisement

Answer

You can use array_agg() to have both the virtual_machines in one row.

Query:

Output:

id name virtual_machines
1 Server1 [{id: 2, name: vm2, serverName: Server1}, {id: 1, name: vm1, serverName: Server1}]

db<fiddle here

With services table :

Query:

Output:

id name virtual_machines
1 Server1 [{id: 2, name: vm2, Services: [{id: null, name: null, vmName: null}], serverName: Server1}, {id: 1, name: vm1, Services: [{id: 1, name: service1, vmName: vm1}], serverName: Server1}]

db<fiddle here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement