Find users who visit only one city instead of multiple cities in MySQL [duplicate]
P粉764785924
2023-07-24 22:47:07
<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>
Please add HAVING condition to your query:
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: