search

Home  >  Q&A  >  body text

Find users who visit only one city instead of multiple cities in MySQL [duplicate]

<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粉764785924P粉764785924521 days ago592

reply all(1)I'll reply

  • P粉147747637

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

    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

    reply
    0
  • Cancelreply