Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select users have more than one distinct records in mysql

Tags:

sql

select

mysql

For a table that holds the records of user's webpages visiting behavior, how can I select users that visit more than one webpages.

The structure of this tables is:

userId        webpageId       visitTime
  0              123            ...
  0              124            ...
  1              123            ...
 ...             ...            ...

I can count using:

SELECT userId, COUNT(DISTINCT webpageId) AS count FROM visits GROUP BY userId;

It gives me the result like:

userId          count
  0               2
  1               1
  2               6
 ...             ...

How can I excute query that gives me the final result like:

userId
  0
  2
 ...

each is user that visit more than one DISTINCT webpages

like image 777
Joey.Z Avatar asked Mar 06 '13 02:03

Joey.Z


1 Answers

just add having clause

SELECT userId, COUNT(DISTINCT webpageId) AS count 
FROM visits 
GROUP BY userId
HAVING COUNT(DISTINCT webpageId) > 1

but if you only what the ID

SELECT userId
FROM visits 
GROUP BY userId
HAVING COUNT(DISTINCT webpageId) > 1
  • SQLFiddle Demo

the reason why you are filtering on HAVING clause and not on WHERE is because, WHERE clause cannot support columns that where aggregated.

like image 86
John Woo Avatar answered Sep 29 '22 09:09

John Woo