如何在sql查询中添加带有unexst的where子句?

时间:2015-01-29 09:59:44

标签: sql database postgresql

我有这样的查询 -

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

由于在查询中放入rowz = 1,此查询无法正常工作?如果我只想要那个结果,其中rowz = 1,那么该怎么做呢。

当我这样做时 -

选择不需要(string_to_array(na.news_category_id,',')):: int rowz         来自news_article;

我的表是 -

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

1 个答案:

答案 0 :(得分:2)

这回答了你的问题:

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;