我正在尝试构建一个执行以下操作的 PostgreSQL 查询,但到目前为止我的努力都是徒劳的。
问题: 有两个表:A 和 B。我想从表 A 中选择所有列(具有列:id、name、description)并将“A.name”列替换为“B”列的值。表 B 中的标题”(具有列:id、table_A_id 标题、langcode),其中 B.table_A_id 为 5,B.langcode 为“nl”(如果有任何行)。
我的尝试:
SELECT A.name,
case when exists(select title from B where table_A_id = 5 and langcode= 'nl')
then B.title
else A.name
END
FROM A, B
WHERE A.id = 5 and B.table_A_id = 5 and B.langcode = 'nl'
-- second try:
SELECT COALESCE(B.title, A.name) as name
from A, B
where A.id = 5 and B.table_A_id = 5 and exists(select title from B where table_A_id = 5 and langcode= 'nl')
我尝试过使用 CASE 和 COALESCE() 但由于我对这两个概念缺乏经验而失败了。
提前致谢。