搜索

首页  >  问答  >  正文

在MySQL中找到仅访问一个城市而不是多个城市的用户 [duplicate]

<p>我有一个包含用户ID、城市和预订日期的表格。我需要找出在一个日期范围内只访问了一个城市而没有访问多个城市的用户。</p> <pre class="brush:php;toolbar:false;">SELECT user_id, city, COUNT(*) as result FROM visits WHERE start_ts >= 1675209600 -- 1675209600 = 01.02.2023 00:00 AND end_ts <= 1676419200 -- 1676419200 = 15.2.2023 00:00 GROUP BY user_id, city</pre> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>city</th> <th>result</th> </tr> </thead> <tbody> <tr> <td>10</td> <td>Munich</td> <td>1</td> </tr> <tr> <td>11</td> <td>Barcelona</td> <td>2</td> </tr> <tr> <td>11</td> <td>Berlin</td> <td>1</td> </tr> <tr> <td>12</td> <td>Barcelona</td> <td>1</td> </tr> <tr> <td>13</td> <td>Prague</td> <td>2</td> </tr> <tr> <td>11</td> <td>Barcelona</td> <td>1</td> </tr> <tr> <td>13</td> <td>Berlin</td> <td>1</td> </tr> </tbody> </table> <p>用户ID 10和12只访问了一个城市。例如,用户ID 11访问了巴塞罗那两次。</p><p>我尝试过使用NOT EXISTING和INNER JOIN。如何获取只访问了一个城市的用户?</p><p><br /></p>
P粉764785924P粉764785924521 天前596

全部回复(1)我来回复

  • P粉147747637

    P粉1477476372023-07-25 10:55:52

    请在您的查询中添加HAVING条件:

    SELECT user_id, city, COUNT(*) as result
    FROM visits 
    WHERE start_ts >= 1675209600 -- 1675209600 = 01.02.2023 00:00
    AND end_ts <= 1676419200 -- 1676419200 = 15.2.2023 00:00
    GROUP BY user_id, city
    HAVING result = 1

    如果您需要仅计算唯一城市的数量,您可以使用COUNT(DISTINCT(city))并将其从分组中移除,如下所示:

    SELECT user_id, city, COUNT(DISTINCT(city)) as result
    FROM visits 
    WHERE start_ts >= 1675209600 -- 1675209600 = 01.02.2023 00:00
    AND end_ts <= 1676419200 -- 1676419200 = 15.2.2023 00:00
    GROUP BY user_id
    HAVING result = 1

    回复
    0
  • 取消回复