I need to return a distinct list of records based on a car keywords search like: \"Alfa 147\"
The problem is that, as I have 3 \"Alfa\" cars, it returns 1 + 3 records (i
The kac is not filtering words... so this joins of kac, kac1 and kac2 will return 3 lines, cause this is the numbers of keywords for this ad
You should remove it..
Try this:
SELECT DISTINCT
c.Id, c.Name /*, COUNT(Number of Ads in the KeywordAdCategories table with those 2 keywords) */
FROM
Categories AS c
INNER JOIN
KeywordAdCategories AS kac1 ON kac1.Keyword_Id = (SELECT Id
FROM Keywords
WHERE Name = 'ALFA')
AND kac1.Category_Id = c.Id
INNER JOIN
KeywordAdCategories AS kac2 ON kac1.Ad_Id = kac2.Ad_Id
AND kac2.Keyword_Id = (SELECT Id
FROM Keywords
WHERE Name = '147')
AND kac2.Category_Id = c.Id
I did a test...
Setting the ambient as
declare @Keywords table(id int,name varchar(max))
insert into @Keywords(id,name)
values (1356,'ALFA')
,(1357,'ROMEO')
,(1358,'145')
,(1373,'147')
declare @Categories table(id int, name varchar(max))
insert into @Categories(id,name)
values (1,'Carros')
,(2,'Motos')
declare @KeywordAdCategories table(Keyword_Id int, ad_Id int,Category_Id int)
insert into @KeywordAdCategories (Keyword_Id , ad_Id,Category_Id)
values (1356, 1017,1)
,(1356, 1018,1)
,(1356, 1019,1)
,(1357, 1017,1)
,(1357, 1018,1)
,(1357, 1019,1)
,(1358, 1017,1)
,(1373, 1019,1)
I run these two queries:
--query 1
SELECT
c.Id, c.Name,COUNT(*) as [count]
FROM
@Categories AS c
INNER JOIN
@KeywordAdCategories AS kac1 ON kac1.Keyword_Id = (SELECT Id
FROM @Keywords
WHERE Name = 'ALFA')
AND kac1.Category_Id = c.Id
GROUP BY
c.Id, c.Name
I get this result set:
Id Name count
----------- ---------- -----------
1 Carros 3
and the second query for two words...
--query 2
SELECT
c.Id, c.Name,COUNT(*) as [count]
FROM
@Categories AS c
INNER JOIN
@KeywordAdCategories AS kac1 ON kac1.Keyword_Id = (SELECT Id
FROM @Keywords
WHERE Name = 'ALFA')
AND kac1.Category_Id = c.Id
INNER JOIN
@KeywordAdCategories AS kac2 ON kac1.Ad_Id = kac2.Ad_Id
AND kac2.Keyword_Id = (SELECT Id
FROM @Keywords
WHERE Name = '147')
AND kac2.Category_Id = c.Id
GROUP BY
c.Id, c.Name
Result set is:
Id Name count
----------- ---------- -----------
1 Carros 1
Is this what you want?