Running this query takes a long time:
SELECT host,ip FROM arecords WHERE ip IN
(SELECT ip FROM arecords GROUP BY ip HAVING COUNT(ip)>1 )
;
(In my arecords table, sometimes there is more than one host on a IP. For these cases, I want to get the hostname+ip)
I have the feeling the sub query is run a lot of times. If I run the sub query, take the results, and replace the sub query with these results, it is fast. I found I can avoid this by using views.
Is there a way of doing it with one query?
[Example SQLfiddle of the result I’d like: http://sqlfiddle.com/#!2/6c1bd/1/0 ]
Try this solution. This will retrieve all rows for each ip that exists in the table more than once. This uses a subselect in
FROM, which is executed once — rather than a subquery in aWHEREwhich gets executed once for each outer row.After the
ips are selected, you join on the same table where theipis equal to theipthat was selected in theFROMsubselect. The join should be fast as it will happen over indexes and the final result is that it will gethosts +ips for only theips having more than one value in the table: