Is it possible to achieve this task with a single MySQL query?
Table urls. Fields {id, url}
1, www.mysite.kom
2, mysite.kom
3, anothersite.kom
Table logs. Fields {id, url_id, group_type - a number in the range of 1..10}
1, 1, 4
2, 1, 4
3, 2, 5
4, 2, 5
5, 3, 9
The result of the query in this example should be: 1 (mysite.com and www.mysite.com = 1)
THE GOAL:
Need to count all distinct urls recorded in logs table, but with a few conditions:
1) Urls with and without www. prefix, like mysite.kom and www.mysite.kom,
should be counted as 1 (not 2).
2) Have group_type in the range of 4..6
3) Now, any of these urls with group_type 4..6, which appear in the list of those with group_type lower than 4 - should be ignored and not counted at all.
The SQL code:
SELECT COUNT(DISTINCT TRIM(LEADING 'www.' FROM b.url))
FROM logs a
INNER JOIN urls b
ON a.url_id = b.id
WHERE (group_type BETWEEN 4 AND 6)
----- and this condition below -----
AND TRIM(LEADING 'www.' FROM b.url)
NOT IN (
SELECT TRIM(LEADING 'www.' FROM b.url)
FROM logs a
INNER JOIN urls b
ON a.url_id = b.id
WHERE (group_type < 4)
)
If my sql query is correct, can it be optimized (to look more compact)?