简体   繁体   English

带有空格的列名上的 Python SQLite INNER JOIN

[英]Python SQLite INNER JOIN on column names with spaces

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.我整天都在尝试对 python 中的 Sqlite DB 进行不同 SQL 查询的许多不同变体,虽然我可以让其中一些工作,但我不知道它们为什么工作或不工作。

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.我尝试使用不使用任何内容、撇号、引号和任何 `s 的不同变体。 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?我不知道何时使用哪些字符的规则,以及它是否特定于我的编码环境/linter?

"LeadDataTable.Lead ID" is a string literal and not the value of a column. "LeadDataTable.Lead ID"是字符串文字,而不是列的值。

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 :在这种情况下,只有Lead ID列需要它们,并且在ON子句中您不能使用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)

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

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