There are four tables: Attributes
, Place_Attributes
, Place_Categories
, and Categories
.
- I need to join
Attributes
andPlace_Attributes
onAttributeId
and selectName
. - I need to join
Categories
andPlace_Categories
onCategoryId
and selectName
. - I need to join these two lists of results on
PlaceId
from thePlace_Attributes
andPlace_Categories
tables.
The problem: The query runs and I get a list of results. I thought the list was correct, but on closer inspection, the list of attributes being returned is longer than the list I was expecting. It does not match what is live on the site. I’m positive it’s my query that’s wrong. The live site is correct.
I tried many different queries to achieve this result and this one is the closest to what I need, but results in the above problem:
-- Step 1: Create a temporary table to store the results
DECLARE @TempResults TABLE (
attributename VARCHAR(255),
categoryname VARCHAR(255)
);
-- Step 2: Insert data into the temporary table
INSERT INTO @TempResults (attributename, categoryname)
SELECT DISTINCT
a.name AS attributename,
c.name AS categoryname
FROM Attributes a
INNER JOIN Place_Attributes pa ON a.id = pa.attributeid
INNER JOIN Place_Categories pc ON pa.PlaceId = pc.placeid
INNER JOIN Categories c ON pc.CategoryId = c.id;
-- Step 3: Select data from the temporary table to view results
SELECT * FROM @TempResults
ORDER BY categoryname;