2014-11-21 11 views
2

假设我已经定义的模型像这样:SQLAlchemy的加入到同一个表上的一列,但还需要从其它列数据结果

class DstEntry(Base): 
    __tablename__ = 'dst_entry' 

    id = Column('id', DBKeyType, primary_key=True) 
    name = Column(String(64)) 
    ip_addr = Column(IPAddress) 
    logical_device_ip = Column(String(64)) 

而且我有数据,像这样:

id name  ip_addr  logical_device_ip 
-------------------------------------------------- 
1 l3dst  3.3.3.3/32 192.168.99.151 
2 httpdst 1.1.1.1/32 192.168.99.152 <=== 
3 httpdst2 2.2.2.0/24 192.168.99.151 
4 dddd  1.1.1.1/32 192.168.99.153 <=== 
5 httpdst 1.1.1.1/32 192.168.99.151 <=== 
6 aadst  4.4.4.4/32 192.168.99.153 

我希望能够进行查询,最终得到的东西,告诉我:

ip_addr  logical_device_ip 
-------------------------------------------------- 
1.1.1.1/32 192.168.99.151, 192.168.99.152, 192.168.99.153 
3.3.3.3/32 192.168.99.151 
2.2.2.0/24 192.168.99.151 
4.4.4.4/32 192.168.99.153 

如何做到这一点与SQLAlchemy的?

回答

0

试试这个:

res = session.query(
     DstEntry.ip_addr, 
     func.group_concat(DstEntry.logical_device_ip) 
     ).group_by(DstEntry.ip_addr) 

for r in res: 
    print r 

注:在结果

  1. logical_device_ip,作为分隔符连接起来。如果你想一个空格字符添加到分离器,这样做反而

    res = session.query(
         DstEntry.ip_addr, 
         func.group_concat(DstEntry.logical_device_ip.op('SEPARATOR')(', ')) 
         ).group_by(DstEntry.ip_addr) 
    
  2. MySQL的原始SQL查询:

    SELECT ip_addr, 
         GROUP_CONCAT(logical_device_ip) AS logical_device_ip 
    FROM dst_entry 
    GROUP BY ip_addr; 
    
相关问题