简体   繁体   English

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

[英]Set a default value for a column in sql query

I have a database where the first table is an "article" table(id, body...) and a second one containing words (word_id, word).我有一个数据库,其中第一个表是“文章”表(id,body ...),第二个包含单词(word_id,word)。 These words are like labels/topics of the articles这些词就像文章的标签/主题

another table connects the previous ones: article_labels(article_id, word_id).另一个表连接前面的表:article_labels(article_id, word_id)。

some articles don't have labels(not included in article_labels table) and the majority of articles have multiple labels.有些文章没有标签(不包含在 article_labels 表中),并且大多数文章都有多个标签。

what I have is a query to get just the labeled articles ( id | body | label1/label2/...)我有一个查询来获取标记的文章(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;

what I want to do is to get all the articles with their labels, if an article is not labeled a default value(eg "unlabeled") is inserted.我想要做的是获取所有带有标签的文章,如果文章没有被标记,则插入默认值(例如“未标记”)。

Thank you in advance!先感谢您!

You can use a sub query for this:您可以为此使用子查询:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM