Question

I need to know, is this the right way to do this:

(SELECT id, name, 1 AS reference FROM antenna WHERE id IN (SELECT antenna_id FROM reference)) 
UNION DISTINCT
(SELECT id, name, 0 AS reference FROM antenna WHERE id NOT IN (SELECT antenna_id FROM reference))

Have been doing it for some time and even though it works perfectly, it is quite ugly.

Was it helpful?

Solution

Off the top of my head, I am not sure it works, test and benchmark:

SELECT antenna.id, antenna.name, CASE WHEN COALESCE(reference.antenna_id, 0)!=0 
THEN 1 ELSE 0 END AS reference FROM antenna LEFT JOIN reference 
ON antenna.id=reference.antenna_id

OTHER TIPS

Yes. It will work. But IN clause gives poor performance as compare to JOIN. Also, IN clause has limit of 1000 records.

Use this query instead-

(SELECT id, name, 1 AS reference FROM antenna a, reference ref
where a.id = ref.antenna_id)
UNION
(SELECT id, name, 0 AS reference FROM antenna a, reference ref
where a.id != ref.antenna_id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top