假设我有一个MySQL表product,如下所示:

+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| id          | varchar(36)  | NO   | PRI | NULL    |       |
| lang        | varchar(255) | YES  |     | NULL    |       |
| description | varchar(255) | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+

我想把这product条信息翻译成几种语言.目前只有description字段是可翻译的,但我们将在future 添加更多可翻译的字段.

为了启用转换,我创建了一个新的表product_translation,如下所示:

CREATE TABLE product_translation (
  id            VARCHAR(36) PRIMARY KEY,
  language_code VARCHAR(10),
  product_id    VARCHAR(36),
  description   VARCHAR(255),
  FOREIGN KEY (product_id) REFERENCES product(id)
);

现在,如果请求的语言是英语或不是英语,我将使用product表的description字段.否则,我会像这样加入productproduct_translation表:

SELECT product.*, 
       product_translation.language_code,
       product_translation.description 
FROM product INNER JOIN product_translation
ON product_translation.product_id = product.id 
WHERE product_translation.language_code = 'fr';

Does it make sense ?
Can I use one SQL statement to retrieve products for any language ?
Would it be better to drop the description field from the product table, copy the data, and always use the join ?

推荐答案

如果请求的语言是英语或不存在,我使用description product表的字段.否则,我就会加入productproduct_translation张桌子

您可以使用COALESCE function in mysql实现这一点

函数的作用是:返回第一个非空的 值在表达式列表中.如果列表中的所有值都求值 设置为NULL,则coalesce()函数返回NULL.

您的查询可以写成:

SELECT product.*, 
       COALESCE(product_translation.language_code, 'en') AS language_code,
       COALESCE(product_translation.description, product.description) AS description
FROM product LEFT JOIN product_translation
ON product_translation.product_id = product.id 
AND product_translation.language_code = 'fr';

从产品中go 掉Description字段会更好吗 表,复制数据,并始终使用连接?

如果您很少转换PRODUCT_INFORMATION;那么您可以保留description字段,否则您可以将其从product表中删除并将数据复制到product_translation表中.

Mysql相关问答推荐

如何在Sequelize中将查询作为选项?

计算符合字段值只能包含一种事件类型这一事实的记录

查询优化并提高性能

使用Workbench时如何添加mysqldump配置标志

按特定顺序匹配 EventS 和下一个 EventA 之前的第一个 Event 之间的记录

MySQL - 事务绑定多个存储过程调用和回滚的简单方法?

无法从mysql数据库获取数据

Mysql时间序列数据的最小值和最大值

如何获取每日登录用户数?

MySQL 使用了错误的索引

如何在不使用子查询的情况下按最小日期计算新用户?

保存SQL查询的中间结果

用两个新列制作表格,按偶数或奇数对另一列进行分类,并将一个类别中的所有偶数和奇数相加

如何使用 sequelize 将复合主键放在连接表中?

通过数据库级​​别本身的查询反序列化

MySQL触发器在某些条件下防止INSERT

基于字符串动态创建 PHP 对象

错误:无法构建 gem 本机扩展(rails 3.2.3 上的 mysql2)

在 Mac 上设置 Laravel php artisan migrate 错误:没有这样的文件或目录

将mysql查询输出存储到shell变量中