我有两张表有数百万条记录需要加入以显示不同语言的结果。我希望使用带有IF条件的查询创建一个视图,但我无法理解哪种方法是正确的。
我需要做的是:如果以下select对于单行具有NULL(换句话说,该行没有deutsch转换)...
SELECT one,two FROM tableA A LEFT JOIN tableB B ON(A.id = B.id)WHERE language ='de'order by xyz
...然后将英文版本放在同一行,所以选择:
SELECT one,two FROM tableA A LEFT JOIN tableB B ON(A.id = B.id)WHERE language ='en'order by xyz
谢谢! 卢卡
答案 0 :(得分:1)
您查询很难遵循,因为您没有别名。我假设它的结构如下:
select a.one. b.two
from tableA a left join
tableb b
on a.id = b.id
where b.language = 'de'
order by xyz
以下提供了适用于MySQL的逻辑:
SELECT a.one,
(case when (select COUNT(*) from b where b.id = a.id and b.language = 'de' and b.two is null) = 0
then bde.two
else bend.two
end) as two
FROM tableA A LEFT JOIN
tableB Bde
ON (A.id=B.id) and
bde.language='de' left join
tableB ben
on ben.language = 'en'
order by xyz
这假设NULL
值存储在B表中。如果它通过连接丢失了,那就更难了,比如:
SELECT a.one,
(case when (select COUNT(*) from a a2 join b b2 on a2.id = b2.id and b2.language = 'de' and b2.two is null) = 0
then bde.two
else bend.two
end) as two
FROM tableA A LEFT JOIN
tableB Bde
ON (A.id=B.id) and
bde.language='de' left join
tableB ben
on ben.language = 'en'
order by xyz