2014-06-30 86 views
1

我有两个简单的表:作者和文章。你可以找到它hereMySQLdb:正确的SQL请求组响应数据

所以,当我执行MySQLdb的查询:

import MySQLdb 
def test_code(): 
    db = MySQLdb.connect(mysql_host, mysql_user, mysql_pass, mysql_base) 
    db.query("select * from `authors` join `articles` on articles.`authorId` = authors.`id`") 
    r = db.store_result() 
    result =() 
    while True: 
     row = r.fetch_row(how=1) 
     if row: 
      result += row 
     else: 
      return result 
print test_code() 

我得到了以下结果:

({ 
    'firstname': 'Alexandro', 
    'Title': 'My life', 
    'lastname': 'Riviera', 
    'articles.id': 6L, 
    'authorId': 1L, 
    'id': 1L 
}, { 
    'firstname': 'Alexandro', 
    'Title': 'My life 2', 
    'lastname': 'Riviera', 
    'articles.id': 7L, 
    'authorId': 1L, 
    'id': 1L 
}, { 
    'firstname': 'Helen', 
    'Title': 'Learn SQL', 
    'lastname': 'Oldgarno', 
    'articles.id': 8L, 
    'authorId': 2L, 
    'id': 2L 
}, { 
    'firstname': 'Helen', 
    'Title': 'SQL for you', 
    'lastname': 'Oldgarno', 
    'articles.id': 9L, 
    'authorId': 2L, 
    'id': 2L 
}, { 
    'firstname': 'Joe', 
    'Title': 'Python', 
    'lastname': 'Smith', 
    'articles.id': 10L, 
    'authorId': 3L, 
    'id': 3L 
}, { 
    'firstname': 'Joe', 
    'Title': 'Python 2', 
    'lastname': 'Smith', 
    'articles.id': 11L, 
    'authorId': 3L, 
    'id': 3L 
}, { 
    'firstname': 'Joe', 
    'Title': 'Python 3', 
    'lastname': 'Smith', 
    'articles.id': 12L, 
    'authorId': 3L, 
    'id': 3L 
}) 

,而不是这个,我想获得athor的文章在字典中作者为,是这样的:

({ 
    'id': 1L, 
    'firstname': 'Alexandro', 
    'lastname': 'Riviera', 
    'articles': [{ 
     'Title': 'My life', 
     'articles.id': 6L 
    }, { 
     'Title': 'My life 2', 
     'articles.id': 7L 
    }] 
}, 

{ 
    'id': 2L, 
    'firstname': 'Helen', 
    'lastname': 'Oldgarno', 
    'articles': [{ 
     'Title': 'Learn SQL', 
     'articles.id': 8L 
    }, { 
     'Title': 'SQL for you', 
     'articles.id': 9L, 
    }], 
}) 

是否有可能得到与正确的SQL请求,或者我这样的结果需要用蟒蛇的方式“用手”来做到这一点?

非常感谢您的帮助!

+2

mysql查询不会返回那样的“嵌套”结构。你必须从mysql那里得到“平坦”的回报,并自己去做。 –

+0

我期待这个:) – user3790902

回答

1

是的,你回答了你自己的问题:MySQL(和许多其他)不是自定义格式的最佳解决方案。使用脚本语言读取查询结果,然后格式化为所需的外观/感觉,这是正确的方法。

+0

我相信有人已经解决了这个问题。 – user3790902

相关问题