I’ve got a many to many relationship between items–itemnames–languages
The itemnames don’t appear for every language.
I’d like to get a result with all the items only represented once, but be able to set the languageId to default to.
For example items 1,2,3 are defined in two languages, and item 4 and 5 have one language each, but the languages are different
[itemid][languageid][name]
1, 1, item1
1, 2, leItem1
2, 1, item2
2, 2, leItem2
3, 1, item3
3, 2, leItem3
4, 1, item4
5, 2, leItem5
I’d like to create a query that only gives me one of each itemID, but allow me to specify which language to prefer, so if I select a languageID of 2, my query would only return item names for that start with ‘leItem’ with the exception of item 4, which should still give me item4
Any ideas how to achieve this with a SELECT?
The theory (how I’m trying to get it to work), is that I create two queries, one for all where languageID matches x , and second where each item is represented (by group or distinct) and then merge the results.
sql for generating the table
-- Languages
CREATE TABLE [Languages] (
[id] INT NOT NULL PRIMARY KEY IDENTITY,
[language] NVARCHAR(20) NOT NULL ,
[languagecode] NVARCHAR(6) NOT NULL
);
-- Items
CREATE TABLE [Items] (
[id] INT NOT NULL PRIMARY KEY IDENTITY,
[ImageId] INT ,
[lastupdate] DATETIME,
[isactive] BIT NOT NULL DEFAULT 'TRUE'
);
-- ItemNames
CREATE TABLE [ItemNames] (
[itemId] INT NOT NULL ,
[languageId] INT NOT NULL ,
[name] NVARCHAR(50) NOT NULL ,
FOREIGN KEY (itemId) REFERENCES Items(id),
FOREIGN KEY (languageId) REFERENCES Languages(id),
PRIMARY KEY ([itemId],[languageId])
);
I would try using a
CASEstatement. Basically the idea is to determine if the preferred language exists and returnnullif it does not. That way you can utilizeISNULLto returned the preferred language (when it is populated) otherwise return the minimum language ID: