如何使用MYSQLdb在Python 2.7中正确创建左连接?

时间:2017-11-20 07:49:42

标签: python mysql mysql-python

我正在尝试使用左连接加入2个表,但有些东西不适合它。

我收到此错误代码:"You have an error in your SQL syntax to use near 'EXAMINED_AIRPORT_AIRPORT',\n EXAMINED_AIRPORT_COUNTRY\n ARRIV`'在第23行“

这是我的代码:

connection = MySQLdb.connect(host='localhost',
        user='adam',
        passwd='',
        db='database1',
        use_unicode=True,
        charset="utf8")
    cursor = connection.cursor()
    query = """     select 
      `ACTUAL_TIME`, 
      `ACTUAL_DAY`, 
      `EXAMINED_AIRPORT_CODE`, 
      `EXAMINED_AIRPORT_AIRPORT`,     
      `EXAMINED_AIRPORT_COUNTRY`, 
      `ARRIVALS/DEPARTURES`, 
      `SCHEDULED_TIME`, 
      `FLIGHT`, 
      `FROM`, 
      `AIRLANE`,
      `AIRCRAFT`, 
      `STATUS`, 
      `FLIGHT_ID_1`, 
      `FLIGHT_ID_2`, 
      `UPLOAD_TIME`
    from OSSZES as a
    left join (
      select 
        `ACTUAL_TIME`
        `ACTUAL_DAY`,
        COALESCE(`EXAMINED_AIRPORT_CODE`, '') as EXAMINED_AIRPORT_CODE 
        `EXAMINED_AIRPORT_AIRPORT`, 
        `EXAMINED_AIRPORT_COUNTRY`, 
        `ARRIVALS/DEPARTURES`, 
        `SCHEDULED_TIME`, 
        `FLIGHT`, 
        `FROM`, 
        `AIRLANE`,
        `AIRCRAFT`, 
        `STATUS`, 
        `FLIGHT_ID_1`, 
        `FLIGHT_ID_2`, 
        `UPLOAD_TIME`
      from OSSZES_CLEAR
    ) as b using (`ACTUAL_DAY`,`EXAMINED_AIRPORT_CODE`,`FLIGHT`,`SCHEDULED_TIME`,`STATUS`)
    where b.EXAMINED_AIRPORT_CODE is null
    into outfile '/tmp/proba.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
        """
    cursor.execute(query)
    connection.commit()
    cursor.close()

1 个答案:

答案 0 :(得分:2)

对字段使用ab。 例如,如果ACTUAL_TIME来自表a(OSSZES),请使用aACTUAL_TIME 同样适用于b表。

select 
  `a`.`ACTUAL_TIME`, 
  `a`.`ACTUAL_DAY`, 
  `a`.`EXAMINED_AIRPORT_CODE`, 
  `a`.`EXAMINED_AIRPORT_AIRPORT`,     
  `a`.`EXAMINED_AIRPORT_COUNTRY`, 
  `a`.`ARRIVALS/DEPARTURES`, 
  `a`.`SCHEDULED_TIME`, 
  `a`.`FLIGHT`, 
  `a`.`FROM`, 
  `a`.`AIRLANE`,
  `a`.`AIRCRAFT`, 
  `a`.`STATUS`, 
  `a`.`FLIGHT_ID_1`, 
  `a`.`FLIGHT_ID_2`, 
  `a`.`UPLOAD_TIME`
from OSSZES as a
left join (
  select 
    `ACTUAL_TIME`
    `ACTUAL_DAY`,
    COALESCE(`EXAMINED_AIRPORT_CODE`, '') as EXAMINED_AIRPORT_CODE 
    `EXAMINED_AIRPORT_AIRPORT`, 
    `EXAMINED_AIRPORT_COUNTRY`, 
    `ARRIVALS/DEPARTURES`, 
    `SCHEDULED_TIME`, 
    `FLIGHT`, 
    `FROM`, 
    `AIRLANE`,
    `AIRCRAFT`, 
    `STATUS`, 
    `FLIGHT_ID_1`, 
    `FLIGHT_ID_2`, 
    `UPLOAD_TIME`
  from OSSZES_CLEAR
) as b using (`ACTUAL_DAY`,`EXAMINED_AIRPORT_CODE`,`FLIGHT`,`SCHEDULED_TIME`,`STATUS`)
where `b`.`EXAMINED_AIRPORT_CODE` is null