为sql查询中的列设置默认值

茴香胺

我有一个数据库,其中第一个表是“文章”表(id,body ...),第二个包含单词(word_id,word)。这些词就像文章的标签/主题

另一个表连接前面的表:article_labels(article_id, word_id)。

有些文章没有标签(不包含在 article_labels 表中),并且大多数文章都有多个标签。

我有一个查询来获取标记的文章(id | body | label1/label2/...)

   select  article_id, body
           group_concat(word SEPARATOR '/') AS labels 
   from article_labels l,
        portfolio_2022.words w,
        articles a
   where a.language='en'
     and l.word_id = w.id
     and a.id = l.article_id 
   group by article_id;

我想要做的是获取所有带有标签的文章,如果文章没有被标记,则插入默认值(例如“未标记”)。

先感谢您!

萨尔曼A

您可以为此使用子查询:

select id, body, coalesce((
    select group_concat(words.word separator '/')
    from article_labels
    join words on article_labels.word_id = words.id
    where article_labels.article_id = articles.id 
), 'unlabeled') as labels
from articles
where language = 'en'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章