postgresql COALESCE内部的位置

sdnqo3pr  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(1)|浏览(114)

我想返回与idlanguage_code都匹配的所有topics_i18n.content_i18n,但如果id存在,但在保存language_code的另一个表中没有对应的行,则返回topics.content
我试过用“COALESCE”

  1. SELECT
  2. topics.id,
  3. COALESCE (topics_i18n.content_i18n, topics.content) content,
  4. topics_i18n.language_code
  5. FROM topics
  6. LEFT JOIN topics_i18n
  7. ON topics.id = topics_i18n.topic_id
  8. WHERE section_id = $1 AND topics_i18n.language_code = $2
  9. ORDER BY position ASC

然而,这不起作用,我觉得我需要一个WHERE内的COALESCE

  1. SELECT
  2. topics.id,
  3. COALESCE (topics_i18n.content_i18n WHERE topics_i18n.language_code = $2, topics.content) content,
  4. topics_i18n.language_code
  5. FROM topics
  6. LEFT JOIN topics_i18n
  7. ON topics.id = topics_i18n.topic_id
  8. WHERE section_id = $1
  9. ORDER BY position ASC

有什么建议可以帮助我解决这个问题吗?

c9x0cxw0

c9x0cxw01#

将语言子表达式从where子句移到on条件中,它应该可以正常工作。我猜这实际上是业务逻辑。下面是经过修改的查询。

  1. SELECT
  2. topics.id,
  3. COALESCE (topics_i18n.content_i18n, topics.content) content,
  4. topics_i18n.language_code
  5. FROM topics
  6. LEFT OUTER JOIN topics_i18n
  7. ON topics.id = topics_i18n.topic_id
  8. AND topics_i18n.language_code = $2
  9. WHERE topics.section_id = $1
  10. ORDER BY position ASC;

相关问题