select users have more than one distinct records in mysql

后端 未结 3 2075
眼角桃花
眼角桃花 2020-12-15 21:11

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:<

相关标签:
3条回答
  • 2020-12-15 21:54

    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.

    0 讨论(0)
  • 2020-12-15 22:02

    Try this:

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

    More: HAVING

    0 讨论(0)
  • 2020-12-15 22:07

    While HAVING is a good approach in this case, remember that queries can be nested:

    SELECT userId, pageCount
    FROM (
        SELECT userId, COUNT(DISTINCT webpageId) AS pageCount
        FROM visits 
        GROUP BY userId) AS n
    WHERE pageCount > 1
    

    The actual query plans may differ, especially if HAVING is an optimized case, but there is no reason why the plans must be different. (Compare plans on the specific RDBMS/version if it is an issue or concern.)

    0 讨论(0)
提交回复
热议问题