Find users who visit only one city instead of multiple cities in MySQL [duplicate]
P粉764785924
P粉764785924 2023-07-24 22:47:07
0
1
496
<p>I have a table with user ID, city and booking date. I need to find out the users who visited only one city and not multiple cities in a date range. </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>User IDs 10 and 12 only visited one city. For example, user ID 11 visited Barcelona twice. </p><p>I have tried using NOT EXISTING and INNER JOIN. How to get users who only visited one city? </p><p><br /></p>
P粉764785924
P粉764785924

reply all(1)
P粉147747637

Please add HAVING condition to your query:

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

If you need to count only the number of unique cities, you can use COUNT(DISTINCT(city)) and remove them from the grouping like this:

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!