在MySQL中找到仅访问一个城市而不是多个城市的用户 [duplicate]
P粉764785924
P粉764785924 2023-07-24 22:47:07
0
1
566
<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粉764785924
P粉764785924

全部回复(1)
P粉147747637

请在您的查询中添加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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板