I'm trying to retrieve some data from the Gaia telescope database (https://gea.esac.esa.int/archive/ : then go on "search" and then in "Advanced (ADQL)" tab). To do so, I use ADQL (which is similar to SQL but applied to astronomical queries).
The first search is to get all star with a condition on their magnitude :
SELECT *
FROM gaiadr2.gaia_source
WHERE phot_g_mean_mag-(0.00652*POWER(bp_rp, 3)-0.08863*POWER(bp_rp, 2)+0.37112*bp_rp+0.00895)<=13
Then if a star validates this condition, I want to get all stars in a circle with a radius of 0.0208 deg (5 * 15 arcseconds). To do so I perform the following search :
SELECT *
FROM gaiadr2.gaia_source
WHERE CONTAINS(POINT('ICRS',gaiadr2.gaia_source.ra, gaiadr2.gaia_source.dec), CIRCLE('ICRS', ra, dec, 0.0208))=1
where ra and dec are the coordinates of a star that satisfy the first request.
The problem is that I have around 9.5 million stars that satisfy the first query so I have 9.5 million queries to do after to get surrounding stars. I wonder if there is a way to merge these two queries. What I mean is the following: I perform the first query and if a star satisfies it then it automatically does the second query to get surrounding stars and add all stars that have satisfied the second condition to the result file. Is there a way to do this? Thanks!
Note: I have added SQL tag because ADQL is similar and if there is a way to do such a conditional search then it will be possible to do the same in ADQL.