Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extending primary table rows based on joined table ids from LEFT JOIN

I need to write query where i need to find devices that fit in specific coordinates, and then extend the results with some devices that are in the same groups as the one that are visible on the map.

The part where i can find the devices and their fitting groups is an easy task where i just perform a left join on both tables like this:

SELECT * 
FROM device 
LEFT JOIN group
ON device.group_id = group.id
WHERE geo_location && ST_MakeEnvelope(10, 30, 30, 50)

But i’m not sure what is the efficient way to add devices to the result that belong to groups of visible devices.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One idea was to select distinct groups from the illustrated query and then again query the device table for the ones that fit in those groups, but it seems to me that this is not the right way.

Any opinion and help is appreciated.

>Solution :

If you don’t need to retrieve any data from the group table, then you can do a self join on table devices while testing the rows with the same group_id :

SELECT g.*
  FROM device AS d
 INNER JOIN devices AS g
    ON g.group_id = d.group_id 
 WHERE d.geo_location && ST_MakeEnvelope(10, 30, 30, 50)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading