如果以下问题可能有更好/不同/共同的解决方案,我正在寻找意见:
我有一个产品数据库,其中包含英文产品的名称(本应用程序的默认语言),我需要翻译名称(如果有的话).
目前我有这个设置:
产品表
CREATE TABLE products ( id serial NOT NULL, "name" character varying(255) NOT NULL, CONSTRAINT products_pkey PRIMARY KEY (id) )
和产品本地化表
CREATE TABLE products_l10n ( product_id serial NOT NULL, "language" character(2) NOT NULL, "name" character varying(255) NOT NULL, CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language), CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id) REFERENCES products (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE )
我使用以下查询来检索本地化产品的列表(在这种情况下为德语),并回退到默认的英文名称:
SELECT p.id, COALESCE(pl.name, p.name) from products p LEFT JOIN products_l10n pl ON p.id = pl.product_id AND language = 'de';
SQL代码是postgres方言.数据存储为UTF-8.
在我看来很好.我可能改变的一件事是你处理语言的方式:这应该是一个单独的表.因此,您将拥有:
CREATE TABLE products_l10n ( product_id serial NOT NULL, language_id int NOT NULL, "name" character varying(255) NOT NULL, CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language), CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id) REFERENCES products (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE CONSTRAINT products_l10n_language_id_fkey FOREIGN KEY (language_id) REFERENCES languages (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE ) CREATE TABLE languages ) id serial not null "language" character(2) NOT NULL )
除此之外,我认为你已经得到了最好的解决方案.