Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Many-to-many duplicate rows

Author  Topic 

Carlsson
Starting Member

3 Posts

Posted - 2011-08-18 : 09:50:42
On a list of parts a user can select one or more parts to exist on their favorit list. How do I get all parts plus an indicator displaying which parts are on the requsting users favorit list?

Parts
--------
ID (PK)
Name

FavoritListMappings
--------
PartID (PK)
FavoritListID (PK)

FavoritLists
--------
ListID (FK)
Name


Query
SELECT * FROM Parts P LEFT JOIN FavoritListMappings F
ON P.ID = F.PartID


Now this returns all parts. But those parts which has been selected as a favorite by one or more users are returned multiple times as they "exist" for each user adding them to their list.
So user, who owns FavoritListID 1, will see the "Table" three times because it exist on two other favorit lists.

Result
ID Name FavoritListID
-------------------------------
1 Table 1
1 Table 2
1 Table 3
2 Chair 1
3 Vase -


Expected result
ID Name FavoritListID
-------------------------------
1 Table 1
2 Chair 1
3 Vase -


How do I go around this?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-18 : 09:53:32
[code]
SELECT ID,Name,f.FavList
FROM Parts p
LEFT JOIN (SELECT PartID,MIN(FavoritListID) AS FavList FROM FavoritListMappings GROUP BY PartID)f
ON p.PartID = f.PartID
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Carlsson
Starting Member

3 Posts

Posted - 2011-08-19 : 02:28:46
Thank you visakh16, just what I needed :-)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-19 : 02:37:09
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -