Home > Enterprise >  Python SQLite INNER JOIN on column names with spaces
Python SQLite INNER JOIN on column names with spaces

Time:07-20

I've been trying many different variations of different SQL queries to an Sqlite DB in python all day, and although I could get some of them to work, I don't know why they did or didn't work.

I can't get the below query to work. I originally used triple quotes so I could make it more readable on multiple lines, but a different query wasn't working that way until I changed it to single apostrophes, so I did the same to the below example.

cur.execute('select "LeadDataTable.Lead ID" AS "Lid", "LeadDataTable.Email", "LEINTable.LeadID", "LEINTable.DLin" from "LeadDataTable" inner join "LEINTable" ON "Lid" = "LEINTable.LeadID" ')
records = cur.fetchall()
print(records)

I've tried to use different variations of using nothing, apostrophes, quotes, and whatever `s are called. Nothing has worked so far. Currently, I get an empty array returned. I was getting an 'ambiguous column name' error, and a 'column doesn't exist' error. however, when I run the queries separately as follows, it works -

cur.execute('select "Lead ID" as "LeadID", Email from LeadDataTable')
records = cur.fetchall()
print(records)

cur.execute('select LeadID, DLin from LEINTable')
records = cur.fetchall()
print(records)

I don't know the rules of when to use which characters, and if it's specific to my coding environment/linter?

CodePudding user response:

"LeadDataTable.Lead ID" is a string literal and not the value of a column.

Use double quotes (or square brackets, or backticks) only when needed.
In this case, only the column Lead ID needs them and in the ON clause you can't use the alias of Lead ID:

cur.execute('select LeadDataTable."Lead ID" AS Lid, LeadDataTable.Email, LEINTable.LeadID, LEINTable.DLin from LeadDataTable inner join LEINTable ON LeadDataTable."Lead ID" = LEINTable.LeadID')

or, make it more readable:

sql = '''
select LeadDataTable."Lead ID" AS Lid, 
       LeadDataTable.Email, 
       LEINTable.LeadID, 
       LEINTable.DLin 
from LeadDataTable inner join LEINTable 
ON LeadDataTable."Lead ID" = LEINTable.LeadID
'''
cur.execute(sql)
  • Related