我有两个简单的表:作者和文章。你可以找到它here .
所以当我执行 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 请求获得这样的结果,或者我需要以 Python 方式“手动”完成?
非常感谢您的帮助!
最佳答案
是的,您回答了您自己的问题:MySQL(和许多其他)不是自定义格式的最佳解决方案。使用脚本语言读取查询结果,然后将其格式化为您想要的外观/感觉是正确的方法。
关于python - MySQLdb : correct SQL request to group response data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24494199/