SQL Server How to join on a linking table?

70gysomp  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(108)

I've created a stored procedure and in there I'm joining a couple tables:

SELECT ...
FROM [Place] AS [P]

JOIN [Timezone] AS [TZ]
     ON [TZ].[TimezoneId] = [P].[TimezoneId]
JOIN [Address] AS [A]
     ON [P].[PlaceId] = [A].[PlaceId]

I have a Category table that has a one-to-one relationship to the Place table and I also have a SubCategory table that has a many-to-many relationship with the Place table that looks like this (created in C#):

Place:

public Guid CategoryId { get; set; }
public Category Category { get; set; }

public IList<SubCategory> SubCategories { get; set; }

SubCategory:

public List<Place> Places { get; set; }

What I'm trying to do is use a @categoryName filter on that stored procedure that would find a match for either the Category table or the SubCategory table, can't be both in the sense that the user can only select one filter at a time in this scenario, think of the category as object 1, 2, 3 and subcategory as object 4, 5, 6.

Confusing names without explanation but that would just make the post longer.

However, in the case of the SubCategory table, it would need to query the many-to-many relationship between the Place table and the SubCategory table.

When I created this relationship, using EF Core, it created a linking table PlaceSubCategory that I want to use in this case and join it, so that I can then query in such a way (even though it is flawed at the moment):

WHERE
    (Category.Name = @categoryName OR SubCategory.Name = @categoryName)

And have one single filter that I can run through both the Category table and the SubCategory table and find a match, and then return the matching result.

However I don't seem to quite get how to do that right and I couldn't really find the information on the web, neither in my book.

46qrfjad

46qrfjad1#

SELECT P.PlaceID,*
FROM [Place] AS [P]
LEFT [Category] as cat on (P.placeid=cat.placeid)
LEFT [SubCategory] as subcat on (P.placeid=subcat.placeid)
LEFT JOIN [Timezone] AS [TZ]
     ON [TZ].[TimezoneId] = [P].[TimezoneId]
LEFT JOIN [Address] AS [A]
     ON [P].[PlaceId] = [A].[PlaceId]
WHERE (cat.Name = @categoryName OR subcat.Name = @categoryName)

相关问题