2014-06-30 44 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

相關問題