Question

SELECT * FROM a, b WHERE ...

Mysql allows duplicate column names in the results of a query. So, in the terminal, none of the column names are prefixed using the above query.

However, I'm using mysqldb in python with the DictCursor. Results are a list of dictionaries where the column names are the keys. Sometimes, the dict cursor automatically prefixes the column name with the table name. As far as I can tell, it does this for the second of two ambiguous column names, but only if the second value is unique. Anyways, I'd like to force the cursor to prefix ALL keys with the table name.

From the mysqldb docs on the fetch.row() function...

The second parameter (how) tells it how the row should be represented. By default, it is zero which means, return as a tuple. how=1 means, return it as a dictionary, where the keys are the column names, or table.column if there are two columns with the same name (say, from a join). how=2 means the same as how=1 except that the keys are always table.column; this is for compatibility with the old Mysqldb module.

So, it seems doable, but I'm not using the fetch.row() function directly... so the question is, how can I cause the mysqldb dict cursor to always use how=2 when it fetches rows?

Was it helpful?

Solution

I'm not a big fan of using * in queries. List your columns and assign your own aliases as needed. As you'll see, I'm also not a fan of implicit joins.

SELECT a.col1 AS acol1,
       a.col2 AS acol2,
       b.col1 AS bcol1,
       b.col2 AS bcol2
    FROM a
        INNER JOIN b
            ON ...
    WHERE...

OTHER TIPS

Given a dict (or some other data structure) which enumerates the tables and fields explicitly, constructing the SQL is not too hard:

import itertools as it

fields={'a':('col1','col2'),'b':('col1','col3')}

fields_sql=', '.join("{t}.{f} as '{t}.{f}'".format(f=f,t=t)
                     for t in fields for f in fields[t])
sql='''SELECT {f}
    FROM a
        JOIN b ON ...
    WHERE ...'''.format(f=fields_sql)
print(sql)

yields

SELECT a.col1 as 'a.col1', a.col2 as 'a.col2', b.col1 as 'b.col1', b.col3 as 'b.col3'
    FROM a
        JOIN b ON ...
    WHERE ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top