【问题标题】:How to add where clause with unnest in sql query?如何在 sql 查询中添加带有 unnest 的 where 子句?
【发布时间】:2015-01-29 09:59:43
【问题描述】:

我有一个这样的查询 -

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

由于在查询中放置了 rowz=1,此查询不起作用?如果我只想要在 unnest 之后 rowz= 1 的结果,该怎么做。

当我这样做时 -

选择 unnest(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

【问题讨论】:

  • 你能发布一些数据样本吗?
  • @mlinth 在问题中添加
  • 你能添加一些输入数据吗? (理想情况下使用 create table 和 insert 语句,所以我们可以尝试运行查询...)

标签: sql database postgresql


【解决方案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;

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2011-05-30
    • 2012-10-09
    相关资源
    最近更新 更多