Postgresql 案例和测试布尔字段

发布于 2024-09-06 15:01:08 字数 644 浏览 0 评论 0原文

首先:我正在运行 postgresql 8.2 并在 pgAdmin 上测试我的查询。

我有一个包含一些字段的表,说:

mytable(
  id integer,
  mycheck boolean,
  someText varchar(200));

现在,我想要一个与此类似的查询:

 select id,
  case when mycheck then (select name from tableA)
       else (select name from tableB) end as mySpecialName,
  someText;

我尝试运行并得到这个:

ERROR: CASE types character varying and boolean cannot be matched
SQL state: 42804

甚至试图欺骗 postgresql 也

case (mycheck::integer) when 0 then

不起作用。

所以,我的问题是:由于 sql 没有 if,只有 case,我应该如何使用布尔字段执行 if ?

First: I'm running postgresql 8.2 and testing my queries on pgAdmin.

I have a table with some fields, say:

mytable(
  id integer,
  mycheck boolean,
  someText varchar(200));

Now, I want a query similary to this:

 select id,
  case when mycheck then (select name from tableA)
       else (select name from tableB) end as mySpecialName,
  someText;

I tried to run and get this:

ERROR: CASE types character varying and boolean cannot be matched
SQL state: 42804

And even trying to fool postgresql with

case (mycheck::integer) when 0 then

didn't work.

So, my question is: since sql doesn't have if, only case, how I'm suppose to do an if with a boolean field?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情丝乱 2024-09-13 15:01:08

您的问题是您的值(thenelse 之后的表达式)不匹配,而不是您的谓词(when 之后的表达式)不匹配。确保 select name from tableAselect name from tableB 返回相同的结果类型。 mycheck 应该是一个布尔值。

我在 PostgreSQL 9.0beta2 上运行了这个查询,并且(除了必须将 from mytable 添加到 SELECT 语句以及创建表 tableAtableB >),并且它没有产生任何类型错误。但是,当我运行以下命令时,我收到一条与您描述的错误消息非常相似的错误消息:

select case when true
           then 1
           else 'hello'::text 
       end;

上面的结果是:

ERROR:  CASE types text and integer cannot be matched

Your problem is a mismatch in your values (expressions after then and else), not your predicate (expression after when). Make sure that select name from tableA and select name from tableB return the same result type. mycheck is supposed to be a boolean.

I ran this query on PostgreSQL 9.0beta2, and (except for having to add from mytable to the SELECT statement as well as creating tables tableA and tableB), and it didn't yield any type errors. However, I get an error message much like the one you described when I run the following:

select case when true
           then 1
           else 'hello'::text 
       end;

The above yields:

ERROR:  CASE types text and integer cannot be matched
还在原地等你 2024-09-13 15:01:08

我刚刚在 PostgreSQL 8 上运行得很好:

select id,
 case when mycheck = true then (...)
      else (...),
 someText;

I just ran this fine on PostgreSQL 8:

select id,
 case when mycheck = true then (...)
      else (...),
 someText;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文