[英]Find users who have visited URL A and B with SQL?
Let's say you have a table with user, url, datetime
, in which each row is a website visit.假设您有一个包含
user, url, datetime
的表,其中每一行都是一次网站访问。
How to find users who have visited both an URL contaning string pattern A and visited an URL containing string pattern B?如何找到既访问过包含字符串模式 A 的 URL 又访问包含字符串模式 B 的 URL 的用户?
The fact it's "containing a string pattern ...", and not a simple equality makes it impossible to use a query with something like事实上它“包含一个字符串模式......”,而不是一个简单的相等性使得不可能使用类似的查询
url in ('action1.php', 'action2.php')
like in SQL querying a customer ID who ordered both product A and B .就像在SQL 中查询同时订购产品 A 和 B 的客户 ID一样。
You can use group by
and having
:您可以使用
group by
并having
:
select user
from t
where url like '%a%' or
url like '%b%'
group by user
having sum(url like '%a%') > 0 and
sum(url like '%b%') > 0;
If you don't want to repeat the comparisons, you can leave out the where
clause or use:如果不想重复比较,可以省略
where
子句或使用:
select user
from (select t.*, (url like '%a%') as has_a, (url like '%n%') as has_b
from t
) t
where has_a or has_b
group by user
having sum(has_a) > 0 and
sum(has_b) > 0;
Assuming "/testing" and "/staging" are the two URL patterns.假设“/testing”和“/staging”是两种 URL 模式。 You can use this
你可以用这个
SELECT user
FROM `table`
WHERE url LIKE '%/testing%' or
url LIKE '%/staging%'
GROUP BY user
HAVING (COUNT(url LIKE '%/testing%') > 0 and COUNT(url LIKE '%/staging%') > 0)
If you need more info on pattern matching you can do a search on "pattern matching SQL" and "SQL regular expression".如果您需要有关模式匹配的更多信息,您可以搜索“模式匹配 SQL”和“SQL 正则表达式”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.