Reputation: 5044
I have 3 tables, namely product, category and productTocategory
Now my requirement is i want to check the products which exists in multiple categories.
i am not getting proper formation of t-sql.
Can anyone please help me build the query, below is my table structure.
Upvotes: 3
Views: 2565
Reputation: 9129
You have to aggregate your many-to-many join table. Then you can use that in any number of ways to get the associate product info as needed.
For example:
CREATE TABLE Product (ProductId INT, Name VARCHAR(10))
CREATE TABLE Category(CategoryId INT, Name VARCHAR(10))
CREATE TABLE ProductToCategory (ProductToCategoryID INT, CategoryID INT, ProductID INT)
GO
INSERT INTO Product VALUES (1,'prod_1'),(2,'prod_2')
INSERT INTO Category VALUES (1,'cat_1'),(2,'cat_2')
INSERT INTO ProductToCategory VALUES (0,1,1),(1,2,1),(1,1,2)
GO
SELECT p.*
,a.CatCount
FROM Product p
INNER JOIN (
SELECT ProductID
,COUNT(CategoryId) CatCount
FROM ProductToCategory
GROUP BY ProductID
HAVING COUNT(*) > 1
) a ON p.ProductId = a.ProductId
GO
DROP TABLE Product
DROP TABLE Category
DROP TABLE ProductToCategory
Upvotes: 4