小编典典

如何在SQL查询中添加带有嵌套的where子句?

sql

我有这样的查询-

select unnest(string_to_array(news_article.news_category_id, ',')):: int rowz
     from news_article) where rowz=1;

由于将rowz = 1放入查询中,因此该查询无法正常工作?如果我只想要在嵌套后rowz = 1的结果该怎么办。

当我这样做时-

从news_article中选择unnest(string_to_array(na.news_category_id,’,’)):: int rowz;

我的桌子是-

Create table news_article(
id                          bigserial NOT NULL PRIMARY KEY,
news_headline               character varying(70) NOT NULL,
news_content_src            character varying(240) NOT NULL,
news_language_id            integer NOT NULL,
news_category_id            character varying(50) NOT NULL,
news_publisher_id           integer NOT NULL references news_publishers(pub_id),
news_date                   timestamp WITH TIME ZONE Default now()
);

然后它给了我这个结果-

rowz
1
2
1
3
2

阅读 218

收藏
2021-03-08

共1个答案

小编典典

这回答了您的问题:

SELECT * FROM
  (SELECT unnest(string_to_array(news_article.news_category_id, ',')):: int rowz
   FROM news_article) AS categories
WHERE rowz = 1;

诀窍是unnest将数组放入一组记录中,然后将其用作子查询。

但是,结果看起来很愚蠢。您是否想要新闻文章的所有详细信息,这些新闻中news_category_id = 1可能包含其他类别?在这种情况下:

SELECT a.*
FROM news_article a
JOIN (SELECT id, unnest(string_to_array(news_article.news_category_id, ',')):: int rowz
      FROM news_article) AS c ON c.id = a.id
WHERE c.rowz = 1;
2021-03-08