2

我正在尝试以下想法。我正在尝试在单个查询中构建一个后备系统。以下是一些背景信息:

posts_table
id, timestamp

posts_content_table
id, post_id, language_id, title, description

这里的目标是查询posts_table,然后在同一个查询中,使用后备系统加入posts_content_table。因此,如果我使用不存在的 language_id 搜索帖子内容,它应该能够回退到包含内容的 language_id。它应该允许多级后备。

例子:

SELECT p.id FROM posts_table AS p 

LEFT OUTER JOIN posts_content_table AS pc ON (p.id=pc.post_id AND pc.language_id=1)
LEFT OUTER JOIN posts_content_table AS pc2 ON (p.id=pc2.post_id AND pc2.language_id=2)
LEFT OUTER JOIN posts_content_table AS pc3 ON (p.id=pc3.post_id AND pc3.language_id=3)

自然会发生的是当它返回不为空的数据时,该数据应用作最终结果。所以这让我想到了案例。我将如何实施 CASES 以这种方式工作?以下就足够了吗?

SELECT p.id, CASE title
WHEN pc.title is Null THEN pc2.title
WHEN pc2.title is Null THEN ps3.title
WHEN pc3.title is Null THEN '-'
END
FROM posts_table AS p 

LEFT OUTER JOIN posts_content_table AS pc ON (p.id=pc.post_id AND pc.language_id=1)
LEFT OUTER JOIN posts_content_table AS pc ON (p.id=pc.post_id AND pc.language_id=2)
LEFT OUTER JOIN posts_content_table AS pc ON (p.id=pc.post_id AND pc.language_id=3)
4

1 回答 1

3

这就是 的目的COALESCE(),它返回其参数的第一个非空值:

SELECT 
  p.id, 
  COALESCE(pc.title, pc2.title, pc3.title, '-') AS title
FROM posts_table AS p 
LEFT OUTER JOIN posts_content_table AS pc ON (p.id=pc.post_id AND pc.language_id=1)
LEFT OUTER JOIN posts_content_table AS pc2 ON (p.id=pc2.post_id AND pc2.language_id=2)
LEFT OUTER JOIN posts_content_table AS pc3 ON (p.id=pc3.post_id AND pc3.language_id=3)

(注意:我修复了你的表别名 - 它们都是pc,我假设你的意思是别名为pc, pc2, pc3

于 2012-07-10T12:51:09.360 回答