简体   繁体   English

如何使用 Python 控制台将 PostGIS SQL SELECT 查询作为图层添加到 QGIS 3 项目?

[英]How to add PostGIS SQL SELECT query as layer to QGIS 3 project using Python console?

I want to add a PostGIS SELECT query as a new layer to a QGIS 3 project using the Python console.我想使用 Python 控制台将 PostGIS SELECT 查询作为新层添加到 QGIS 3 项目。

It is a simple process to do this using the SQL Window in the DB Manager of QGIS.使用 QGIS 数据库管理器中的 SQL 窗口执行此操作是一个简单的过程。 Here you can create a layer from any SQL query of a PostGIS enabled PostgreSQL database.在这里,您可以从启用 PostGIS 的 PostgreSQL 数据库的任何 SQL 查询创建图层。

The following works for adding an entire PostGIS table and I'm aware a filter can be added by providing a fourth argument to uri.setDataSource().以下适用于添加整个 PostGIS 表,我知道可以通过向 uri.setDataSource() 提供第四个参数来添加过滤器。 However, this method, to my knowledge, does not allow you to do multi table queries and joins.但是,据我所知,这种方法不允许您进行多表查询和连接。

from qgis.core import *
from qgis.core import QgsVectorLayer, QgsDataSourceUri
from qgis.core import QgsProject

uri = QgsDataSourceUri()
uri.setConnection("localhost", "5432", "my_database", "postgres", "password")

uri.setDataSource("public", "my_table", "geom")

vlayer = QgsVectorLayer(uri.uri(), "my_new_layer", "postgres")
QgsProject.instance().addMapLayer(vlayer, True)

Ideally I would like to replace "my_table" with an SQL query like SELECT * FROM my_table .理想情况下,我想用SELECT * FROM my_table之类的 SQL 查询替换"my_table" This would allow you to extend functionality to more complicated queries like:这将允许您将功能扩展到更复杂的查询,例如:

SELECT * FROM my_table_1
JOIN my_table_2 ON my_table_1.foreign_key = my_table_2.primary_key;

The eventual goal is to then implement this code in a QGIS plugin.最终目标是在 QGIS 插件中实现此代码。

Any help would be much appreciated!任何帮助将非常感激!

I found the solution here:我在这里找到了解决方案:

https://gis.stackexchange.com/a/197800 https://gis.stackexchange.com/a/197800

Simply, you must leave the schema blank and include it in the SQL query instead.简单地说,您必须将架构留空并将其包含在 SQL 查询中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM