拼命寻找解决方案。我有基本表和翻译表,需要通过连接进行选择,但是当行没有翻译时->选择默认语言翻译。
我有表products
和products_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 | +------------+------+------------+
需要:
'en'
=>时将返回经过'en'
翻译的行'es'
=>时,如果可能,将返回带有'es'
的行,否则=>返回'en'
。 谢谢。
答案 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
转换(如果可用),否则返回默认值。