title: Get table name for field in database result in Python (PostgreSQL)
body: <p>I'm trying to get table name for field in result set that I got from database (Python, Postgres). There is a function in PHP to get table name for field, I used it and it works so I know it can be done (in PHP). I'm looking for similar function in Python.</p>
  
  <p><a href="http://php.net/manual/en/function.pg-field-table.php" rel="nofollow">pg_field_table()</a> function in PHP gets results and field number and "returns the name of the table that field belongs to". That is exactly what I need, but in Python.</p>
  
  <p>Simple exaple - create tables, insert rows, select data:</p>
  
  <pre><code>CREATE TABLE table_a (
      id INT,
      name VARCHAR(10)
  );
  
  CREATE TABLE table_b (
      id INT,
      name VARCHAR(10)
  );
  
  INSERT INTO table_a (id, name) VALUES (1, 'hello');
  INSERT INTO table_b (id, name) VALUES (1, 'world');
  </code></pre>
  
  <p>When using <code>psycopg2</code> or <code>sqlalchemy</code> I got right data and right field names but without information about table name.</p>
  
  <pre><code>import psycopg2
  
  query = '''
      SELECT *
      FROM table_a A
      LEFT JOIN table_b B
          ON A.id = B.id
  '''
  
  con = psycopg2.connect('dbname=testdb user=postgres password=postgres')
  cur = con.cursor()
  cur.execute(query)
  
  data = cur.fetchall()
  print('fields', [desc[0] for desc in cur.description])
  print('data', data)
  </code></pre>
  
  <p>The example above prints field names. The output is:</p>
  
  <pre><code>fields ['id', 'name', 'id', 'name']
  data [(1, 'hello', 1, 'world')]
  </code></pre>
  
  <p>I know that there is <code>cursor.description</code>, but it does not contain table name, just the field name.</p>
  
  <p>What I need - some way to retrieve table names for fields in result set when using raw SQL to query data.</p>
  
  <p><strong>EDIT 1</strong>: I need to know if "hello" came from "table_a" or "table_b", both fields are named same ("name"). Without information about table name you can't tell in which table the value is.</p>
  
  <p><strong>EDIT 2</strong>: I know that there are some workarounds like SQL aliases: <code>SELECT table_a.name AS name1, table_b.name AS name2</code> but I'm really asking how to retrieve table name from result set.</p>
  
  <p><strong>EDIT 3</strong>: I'm looking for solution that allows me to write any raw SQL query, sometimes <code>SELECT *</code>, sometimes <code>SELECT A.id, B.id ...</code> and after executing that query I will get field names and table names for fields in the result set.</p>