I have a problem when obtaining the records of a DB through a many-to-many relationship, I have the following tables:
At the time of extracting the data from the cpu, there are cpu's that have several network cards, so I have a many-to-many relationship, the problem is that I don't know how to obtain the network cards without repeating the cpu.
The query I make is the following:
SELECT cpu.id_cpu, nic.mac, nic.dir_ip FROM cpu
JOIN activo_fijo ON cpu.id_activo = activo_fijo.id_activo
JOIN nic_cpu ON nic_cpu.id_cpu = cpu.id_cpu
JOIN nic ON nic.id_nic = nic_cpu.id_nic;
The query returns the following:
As you can see, the record with id_cpu: 39 is repeated since that cpu has 2 network cards.
What I would like to obtain is this data in a single record, or in any case omit a network card, since I have to list all the existing cpu's and in this case some would be repeated, since there are several cpus with two network cards;
Is there a way to do it in SQL or PHP?
I am using PHP as programming language and postgresql as DB.
Maybe you are looking for this:
You can use the function
string_agg
to concatenatemac
anddir_ip
. Namely:What about using DISTINCT
Or Using a Left join
Op 3: Group by