group_concat函数中的未知列错误

时间:2015-10-14 20:41:56

标签: python mysql sqlalchemy

我正在编写一个活动仪表板,我正在努力加入表格以建立层次关系,这样我就可以获得最新的活动。除了下面的group_concat函数之外,我能够从数据库中获取查询。 (我包括AutoEscalationDB类供参考,因为这是类中所有函数访问现有数据库的方式。该类中的其他代码被编辑,但它与此问题无关。)< / p>

from app import app

from sqlalchemy import create_engine, or_, func
from sqlalchemy import *
from sqlalchemy.sql import expression
from sqlalchemy.orm import scoped_session, aliased, sessionmaker, relationship
from sqlalchemy.types import TIMESTAMP, INTEGER
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm.exc import FlushError
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.ext import compiler
from sqlalchemy.sql import ColumnElement
from sqlalchemy.sql.expression import FunctionElement, ClauseElement

class event_id(ColumnElement):
    type = INTEGER()

class group_concat(ColumnElement):
    def __init__(self, col1, col2, separator):
        self.col1 = col1
        self.col2 = col2
        self.type = col1.type
        self.separator = separator

separator = "','"

class AutoEscalationDB(object):

    def __init__(self, host=app.config['MYSQL_DATABASE_HOST'],
                 port=app.config['MYSQL_DATABASE_PORT'],
                 user=app.config['MYSQL_DATABASE_USER'],
                 passwd=app.config['MYSQL_DATABASE_PASSWORD'],
                 db=app.config['MYSQL_DATABASE_DB'],
                 short_retry=5, lifetime_retry=25,
                 socket=app.config['MYSQL_DATABASE_SOCKET']):

        self.URI = 'mysql://%s:%s@%s:%s/%s?unix_socket=%s' %(user, passwd, host, port, db, socket)
        self.create_model()
        session_factory = sessionmaker(bind=self.engine)
        self.session = scoped_session(session_factory)
        self.methods = {
            1: self.Emails,
            2: self.Phones,
        }

    @compiler.compiles(group_concat, 'mysql')
    def compile_group_concat(element, compiler, **kw):
        return "GROUP_CONCAT(%s ORDER BY %s SEPARATOR %s)" % (
                    compiler.process(element.col1),
                    compiler.process(element.col2),
                    separator
               )

   def get_escalations(self, event_id=None, **kwargs):
        es1 = aliased(self.Event_statuses)
        es2 = aliased(self.Event_statuses)
        e1 = aliased(self.Events)
        e2 = aliased(self.Events)
        m = MetaData()
        separator = "','"
        t = Table('e2', m, Column('event_id', Integer), Column('event_id', Integer))
        eid = group_concat(t.c.event_id, t.c.event_id, ',').compile(bind=create_engine('mysql://'))
        query = self.session.query(e1).\
            from_self(e1.parent_event_id,
                e1.event_id,
                es1.event_status,
                e1.event_name,
                eid.string,
                e1.reporter,
                e1.message,
                self.Users.user_id,
                self.Users.username,
                self.Users.first_name,
                self.Users.last_name,
                e1.timestamp
            ).outerjoin(e2, e2.parent_event_id == e1.event_id).\
            join(es1, es1.event_statuses_id == e1.event_status_id).\
            outerjoin(es2, e2.event_status_id == es2.event_statuses_id).\
            outerjoin(self.Users, self.Users.user_id == e1.user_id)

        results = {}

        for row in query:
            row = row._asdict()
            if row['event_status'] in results.keys():
                results[row['event_status']].append(row)
            else:
                results[row['event_status']] = [row]

        return True, results

当我点击网址时出现此错误:

OperationalError: (_mysql_exceptions.OperationalError) (1054, "Unknown
column 'e2.event_id' in 'field list'") [SQL: u"SELECT
anon_1.events_1_parent_event_id AS anon_1_events_1_parent_event_id,
anon_1.events_1_event_id AS anon_1_events_1_event_id,
event_statuses_1.event_status AS event_statuses_1_event_status,
anon_1.events_1_event_name AS anon_1_events_1_event_name,
GROUP_CONCAT(e2.event_id ORDER BY e2.event_id SEPARATOR ','),
anon_1.events_1_reporter AS anon_1_events_1_reporter, 
anon_1.events_1_message AS anon_1_events_1_message, users.user_id AS 
users_user_id, users.username AS users_username, users.first_name AS  
users_first_name, users.last_name AS users_last_name, 
anon_1.events_1_timestamp AS anon_1_events_1_timestamp \nFROM (SELECT 
events_1.event_id AS events_1_event_id, events_1.event_type_id AS 
events_1_event_type_id, events_1.reporter AS events_1_reporter, 
events_1.parent_event_id AS events_1_parent_event_id, 
events_1.property_id AS events_1_property_id, events_1.event_name AS 
events_1_event_name, events_1.event_status_id AS 
events_1_event_status_id, events_1.escalation_type_id AS 
events_1_escalation_type_id, events_1.timestamp AS events_1_timestamp, 
events_1.user_id AS events_1_user_id, events_1.message AS 
events_1_message, events_1.group_id AS events_1_group_id, 
events_1.shift_id AS events_1_shift_id \nFROM events AS events_1) AS 
anon_1 LEFT OUTER JOIN events AS events_2 ON events_2.parent_event_id =
anon_1.events_1_event_id INNER JOIN event_statuses AS event_statuses_1 ON 
event_statuses_1.event_statuses_id = anon_1.events_1_event_status_id LEFT 
OUTER JOIN event_statuses AS event_statuses_2 ON events_2.event_status_id
= event_statuses_2.event_statuses_id LEFT OUTER JOIN users ON 
users.user_id = anon_1.events_1_user_id"]

如果我注释掉eid.string,它会按原样返回查询:

SELECT anon_1.events_1_parent_event_id AS
anon_1_events_1_parent_event_id, anon_1.events_1_event_id AS 
anon_1_events_1_event_id, event_statuses_1.event_status AS 
event_statuses_1_event_status, anon_1.events_1_event_name AS 
anon_1_events_1_event_name, anon_1.events_1_reporter AS 
anon_1_events_1_reporter, anon_1.events_1_message AS 
anon_1_events_1_message, users.user_id AS users_user_id, users.username 
AS users_username, users.first_name AS users_first_name, users.last_name 
AS users_last_name, anon_1.events_1_timestamp AS 
anon_1_events_1_timestamp 
FROM (SELECT events_1.event_id AS events_1_event_id, 
events_1.event_type_id AS events_1_event_type_id, events_1.reporter AS 
events_1_reporter, events_1.parent_event_id AS events_1_parent_event_id,
events_1.property_id AS events_1_property_id, events_1.event_name AS 
events_1_event_name, events_1.event_status_id AS 
events_1_event_status_id, events_1.escalation_type_id AS 
events_1_escalation_type_id, events_1.timestamp AS events_1_timestamp, 
events_1.user_id AS events_1_user_id, events_1.message AS 
events_1_message, events_1.group_id AS events_1_group_id, 
events_1.shift_id AS events_1_shift_id 
FROM events AS events_1) AS anon_1 LEFT OUTER JOIN events AS events_2 ON 
events_2.parent_event_id = anon_1.events_1_event_id JOIN event_statuses
AS event_statuses_1 ON event_statuses_1.event_statuses_id = 
anon_1.events_1_event_status_id LEFT OUTER JOIN event_statuses AS
event_statuses_2 ON events_2.event_status_id =
event_statuses_2.event_statuses_id LEFT OUTER JOIN users ON users.user_id = anon_1.events_1_user_id

如果我坚持使用&#39; print eid&#39;声明,它返回这个,应该是正确的:

GROUP_CONCAT(e2.event_id ORDER BY e2.event_id SEPARATOR ',')

我尝试复制的SQL查询是:

SELECT
e1.parent_event_id,
e1.event_id,
es1.event_status,
e1.event_name,
GROUP_CONCAT(e2.event_id ORDER BY e2.event_id SEPARATOR ', ') AS child_events,
e1.reporter,
e1.message,
u1.user_id,
u1.username,
u1.first_name,
u1.last_name,
e1.timestamp
FROM events e1
LEFT JOIN events e2 ON (e2.parent_event_id = e1.event_id)
JOIN event_statuses es1 ON (es1.event_statuses_id = e1.event_status_id)
LEFT JOIN event_statuses es2 ON (es2.event_statuses_id = e2.event_status_id)
LEFT JOIN users u1 ON (u1.user_id = e1.user_id);

我已确认查询本身有效。

我怀疑这部分是group_concat语句:

.compile(bind=create_engine('mysql://'))

正在创建一个新的mysql引擎,而不是绑定到现有数据库,因此无法从Events表中找到event_id列。不幸的是,这不是我的代码,而且我是sqlalchemy的新手,所以我在黑暗中进行拍摄。任何建议都是最受欢迎的,因为我已经在这里停顿了几天而且我被困住了。提前谢谢!

0 个答案:

没有答案