You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PostgreSQL中将‘真值’‘假值’字符串转换为布尔值?

解决方案

你的核心需求是判断指定用户是否订阅了每个分类,返回布尔类型的is_subscribed字段。之前的尝试错误在于试图将字符串类型的person_name转换为布尔值,这不符合PostgreSQL的类型转换规则(只有'true'/'false'等特定字符串才能直接转布尔)。

正确的SQL语句

select
    c.id as id,
    c.category_name as category_name,
    cs.person_id is not null as is_subscribed
from category c
left join category_subscription cs 
    on c.id = cs.category_id 
    and cs.person_id = 1 -- 指定要查询的用户ID,对应数据里的george(id=1)

逻辑说明

  1. 以category表为主表,使用左连接关联category_subscription表,确保所有分类都会被返回,不会遗漏未订阅的分类。
  2. 在连接条件中加入cs.person_id = 1,仅筛选当前用户的订阅记录,避免关联其他用户的数据。
  3. 通过cs.person_id is not null生成布尔值:如果存在对应的订阅记录,cs.person_id不为空,结果为true;否则为false。

执行结果

该查询会返回你预期的结果:

[
    {
        "id": 10,
        "category_name": "homework",
        "is_subscribed": true
    },
    {
        "id": 20,
        "category_name": "promotion",
        "is_subscribed": false
    },
    {
        "id": 30,
        "category_name": "delivery",
        "is_subscribed": true
    }
]

内容的提问来源于stack exchange,提问作者Mike K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 06:12:42