【问题标题】:showing articles using category filter sql使用类别过滤器 sql 显示文章
【发布时间】:2021-06-28 10:00:51
【问题描述】:

我想选择包含我正在使用 typeorm ( SQL ) 的特定类别的文章 假设我有

articleTable: [
    {
      id: 1,
      title: 'string'
    },
    {
      id: 2,
      title: 'string'
    }
];

categoryTable: [
    {
      id: 1,
      title: 'string'
    }, {
      id: 2,
      title: 'string'
    }
]

article_categories: [
    {
      categoryId: 1,
      articleId: 2
    },{
      categoryId: 1,
      articleId: 1
    },{
      categoryId: 2,
      articleId: 2
    }
]

所以问题是我想选择所有具有确切类别 = [1,2] 等的文章 这意味着如果一篇文章只有类别 1,我不想选择它。

使用此查询,我得到了结果,但它的 id 不完全匹配,而是返回分别具有 id 1 和 2 的文章

async filterData(filterArticleDto: FilterArticlesDto, categoryIds: number[]) {
const qb = this.createQueryBuilder('article');
qb.distinct(true);
if (categoryIds.length) {
  qb.innerJoin(
    'article.categories',
    'categories',
    `categories.category IN (:...ids)`,
    {
      ids: categoryIds,
    },
  );
  qb.leftJoinAndSelect('categories.category', 'catsData');
}
qb.take(filterArticleDto.limit);
return await qb.getMany();

}

【问题讨论】:

    标签: sql node.js postgresql typeorm


    【解决方案1】:

    原始 sql 查询

    SELECT article.*
    FROM articles AS article
    WHERE EXISTS
      (SELECT count(DISTINCT category_id)
      FROM article_categories AS subcts
      WHERE subcts.article_id = article.id
       AND subcts.category_id IN (1,
                                  2)
     HAVING count(DISTINCT category_id) = 2)
    

    https://dbfiddle.uk/?rdbms=postgres_12&fiddle=86f8d3a8bdc9248a918a4c37d8da5ea0

    SELECT article.*
    FROM articles AS article
    INNER JOIN
    (SELECT article_id,
          array_agg(category_id) AS cts
    FROM article_categories
    GROUP BY article_id) AS category ON article.id = category.article_id
    WHERE ARRAY[1,
            2::integer] = category.cts
    

    https://dbfiddle.uk/?rdbms=postgres_12&fiddle=fdde52c1d11d69b690f9fe9345272786

    【讨论】:

    • 小心那个数组版本。如果不对 array_agg 进行排序,cts 可能会是 ARRAY[2,1],这将是不匹配的。例如,使用 ARRAY[1,2]
    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2014-10-03
    • 2021-12-24
    相关资源
    最近更新 更多