检查 PostgreSQL 表格列中的值并返回布尔值

3
我正在学习SQL,如果这很重复,我很抱歉,但我已经搜索过了,没有找到答案。使用Python编写,使用PostgreSQL数据库。
我想检查我的数据库中的一个表格,看看“Port”列是否包含特定位置。我可以通过交互方式完成此操作,但它返回一个表结果,例如:
select exists(select 1 from ref_locations where "Port"='ORAN');

它返回:
exists
-------
t
(1 row)

我希望它只返回一个布尔值,并且我想在我的Python脚本中实现。 我的Python脚本中有:
exists = False
cnx.execute("""select exists(select 1 from ref_locations where "Port"='BAKU');""")
print "Exists: ",exists

但存在总是充满了虚假。非常感谢您的帮助。

print "Exists: ",exists your exists variable is not changed by the result of the query. You need to retrieve the result from the query, and assign it to your variable. There probably is some function in your cursor, like exists = cnx.get_result(); - wildplasser
谢谢!非常好的答案。在我处理这个过程中,我意识到由于我正在测试许多单词是否存在于我的“Port”表中,所以将表读入哈希表或Pandas表中实际上比每次查询数据库更快。 - Callie
2个回答

1
存在许多变体,但最简单的是:


select count(*) > 0 from ref_locations where "Port"='ORAN'

1

你的postgresql语句没有问题,尽管你可以将它缩短到这样:

select exists(select from ref_locations where Port='ORAN');

你遇到的问题是执行语句的结果没有被分配给任何变量。考虑尝试以下方法(在执行语句之后):
exists = cnx.fetchone()

或者只是

print cnx.fetchone()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接