Finden Sie Benutzer, die nur eine Stadt statt mehrerer Städte in MySQL besuchen [Duplikat]
P粉764785924
P粉764785924 2023-07-24 22:47:07
0
1
538
<p>Ich habe eine Tabelle mit Benutzer-ID, Stadt und Buchungsdatum. Ich muss die Benutzer herausfinden, die nur eine Stadt und nicht mehrere Städte in einem Datumsbereich besucht haben. </p> <pre class="brush:php;toolbar:false;">SELECT Benutzer-ID, Stadt, COUNT(*) als Ergebnis VON Besuchen WO start_ts >= 1675209600 -- 1675209600 = 01.02.2023 00:00 AND end_ts <= 1676419200 -- 1676419200 = 15.2.2023 00:00 GROUP BY Benutzer-ID, Stadt</pre> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>Stadt</th> <th>Ergebnis</th> </tr> </thead> <tbody> <tr> <td>10</td> <td>München</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>Prag</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>Die Benutzer-IDs 10 und 12 haben nur eine Stadt besucht. Beispielsweise besuchte Benutzer-ID 11 zweimal Barcelona. </p><p>Ich habe versucht, NOT EXISTING und INNER JOIN zu verwenden. Wie gewinne ich Benutzer, die nur eine Stadt besucht haben? </p><p><br /></p>
P粉764785924
P粉764785924

Antworte allen(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
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!