MYSQL表,table_tr SELECT默认语言,当翻译不可用时

时间:2019-03-14 00:21:40

标签: mysql sql database multilingual

拼命寻找解决方案。我有基本表和翻译表,需要通过连接进行选择,但是当行没有翻译时->选择默认语言翻译。

我有表productsproducts_tr

产品

+----+-------+---------+-------------+
| id | stock | visible | category_id |
+----+-------+---------+-------------+
| 10 | 5     | 1       | 1           |
| 1  | 0     | 1       | 2           |
| 5  | 2     | 1       | 2           |
+----+-------+---------+-------------+

products_tr

+------------+------+------------+
| product_id | lang | name       |
+------------+------+------------+
| 10         | en   | Blue car   |
| 10         | es   | Carro azul |
| 1          | en   | Red car    |
| 5          | en   | Yellow car |
+------------+------+------------+

需要:

  • 选择lang 'en' =>时将返回经过'en'翻译的行
  • 当选择lang 'es' =>时,如果可能,将返回带有'es'的行,否则=>返回'en'

谢谢。

1 个答案:

答案 0 :(得分:1)

一种解决方案是两次JOIN转换表:

SELECT p.*, COALESCE(t1.name, t2.name) name
FROM products p
LEFT  JOIN products_tr t1 ON t1.product_id = p.id AND t1.lang = 'es'
INNER JOIN products_tr t2 ON t2.product_id = p.id AND t1.lang = 'en'

LEFT JOIN尝试引入与es转换对应的记录,而INNER JOIN选择默认值。然后COALESCE()调用返回es转换(如果可用),否则返回默认值。