简体   繁体   中英

Read from a database view rather than a table using SQL

I am trying to read data from a view that I have created based on other views in my database using Python.

Database set-up:

Redshift-postgres
  dev
    Schemas
      schema_name
        Tables
          table_name
        Views
          view_name

Python code:

connection=psycopg2.connect("dbname=dev host=redshift.amazonaws.com port=5439 user=user password=password")

cursor = connection.cursor()
schema = "SELECT count(*) FROM schema_name.table_name;"
schema2 = "SELECT count(*) FROM schema_name.view_name;"
result = pd.read_sql(schema, connection)

When I run the code with schema it returns data from a table but when I try to run schema2 it does not return anything and no error message is provided. The script does not stop it just idles.

Am I doing something wrong when trying to get data from a view rather than a table?

UPDATE

When I run schema2 = "SELECT * FROM INFORMATION_SCHEMA.TABLES;" it does return the following:

table_catalog    table_schema   table_name  table_type 
dev              schema_name    view_name         VIEW    

It lists the view I am trying to read data from.

I created the view like so:

CREATE OR REPLACE VIEW schema_name.view_name
AS SELECT *
        CASE
            WHEN statement
            ELSE false
        END AS column_name, 

   FROM schema_name.another_view_name
   LEFT JOIN schema_name.another_view_name_2 data_1 ON data_2 = data_3
   LEFT JOIN schema_name.another_view_name_3 data_4 ON data_5 = data_6

I have named irelevant data data_x where I join the views based on some conditions.

Turned out that amazon redshift DB got clogged up and had 5 queries that ran for 4 days with no response. Anyhow, I still find that reading from a view with 2 left joins takes like 3 hours to read which is not how it should work. The view has only 1.2m rows. Thank you for your suggestions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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