2

I have two tables with web traffic that I am joining and visualizing on a map.

I am trying to write a counter that creates a query result with a count of the number of times a particular IP address shows up in the logs. I think this will take the form of a subquery that returns the count of rows of the specific row the main query is selecting.

When I run the following query, the error I get is more than one row returned by a subquery used as an expression.

select
squarespace_ip_addresses.ip,
squarespace_ip_addresses.latitude,
squarespace_ip_addresses.longitude,
st_SetSrid(ST_MAKEPOINT(squarespace_ip_addresses.longitude, squarespace_ip_addresses.latitude), 4326) as geom,
(select count(hostname) from squarespace_logs group by hostname) as counter,
squarespace_logs.referrer
from
squarespace_ip_addresses
left outer join
squarespace_logs
on
squarespace_ip_addresses.ip = squarespace_logs.hostname

Something that has been suggested to me is a subquery in a select that filters by the main query output runs that query for every row.

Does anyone have any insights?

1 Answer 1

2

Aggregate the data in a derived table (a subquery in FROM clause):

select
    a.ip,
    a.latitude,
    a.longitude,
    st_SetSrid(ST_MAKEPOINT(a.longitude, a.latitude), 4326) as geom,    
    c.count,
    l.referrer
from squarespace_ip_addresses a
left join squarespace_logs l on a.ip = l.hostname
left join (
    select hostname, count(*)
    from squarespace_logs
    group by hostname
    ) c on a.ip = c.hostname
Sign up to request clarification or add additional context in comments.

5 Comments

So basically this is joining three tables together and gets around the multiple returned columns problem by just accepting that you will get two columns back and joining them. Is that right?
Also why is hostname necessary in select hostname, count(*) in the subquery? I don't understand why it can't just be select count(*).
Basically yes. hostname in the subquery is for joining with the main table.
How would I extend this to query only rows that have a count greater than a given number?
Add where count > 10 at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.